使用字节伙伴API进行刷新方法参数



我正在执行执行过程中需要访问方法参数的项目。是否可以使用字节好友框架打印方法参数?高度赞赏使用Javaagent上的任何示例代码。

是的,这是可能的。您可以使用MethodDelegationAdvice注入代码,然后使用@AllArguments注释来持有实际参数。

问题是,如何在项目中创建代码?您可以使用AgentBuilder使用Java代理,也可以使用ByteBuddy实例创建代理子类。请参阅文档和上述类Javadoc,以了解这是如何完成的。

这是一个可以使用MethodDelegation实现的示例。我用它来测量方法的执行时间。我特别没有开始删除额外的代码,因为我想更充分地揭示Byte Buddy的功能。

    package md.leonis.shingler;
    import net.bytebuddy.agent.ByteBuddyAgent;
    import net.bytebuddy.agent.builder.AgentBuilder;
    import net.bytebuddy.implementation.MethodDelegation;
    import net.bytebuddy.implementation.bind.annotation.AllArguments;
    import net.bytebuddy.implementation.bind.annotation.Origin;
    import net.bytebuddy.implementation.bind.annotation.RuntimeType;
    import net.bytebuddy.implementation.bind.annotation.SuperCall;
    import net.bytebuddy.matcher.ElementMatchers;
    import java.lang.instrument.Instrumentation;
    import java.lang.reflect.Method;
    import java.util.Arrays;
    import java.util.concurrent.Callable;
    import java.util.stream.Collectors;
    public class MeasureMethodTest {
        public static void main(String[] args) throws InterruptedException {
            premain(ByteBuddyAgent.install());
            for (int i = 0; i < 4; i++) {
                SampleClass.foo("arg" + i);
            }
        }
        public static void premain(Instrumentation instrumentation) {
            new AgentBuilder.Default()
                    .type(ElementMatchers.nameStartsWith("md.leonis.shingler"))
                    .transform((builder, type, classLoader, module) ->
                            builder.method(ElementMatchers.any()).intercept(MethodDelegation.to(AccessInterceptor.class))
                    ).installOn(instrumentation);
        }
        public static class AccessInterceptor {
            @RuntimeType
            public static Object intercept(@Origin Method method, @SuperCall Callable<?> callable, @AllArguments Object[] args) throws Exception {
                long start = System.nanoTime();
                try {
                    return callable.call();
                } finally {
                    if (method.getAnnotationsByType(Measured.class).length > 0) {
                        String params = Arrays.stream(args).map(Object::toString).collect(Collectors.joining(", "));
                        System.out.println(method.getReturnType().getSimpleName() + " " + method.getName() + "("+ params +") took " + ((System.nanoTime() - start) / 1000000) + " ms");
                    }
                }
            }
        }
        public static class SampleClass {
            @Measured
            static void foo(String s) throws InterruptedException {
                Thread.sleep(50);
            }
        }
    }

此示例测量md.leonis.shingler软件包中所有方法的执行时间,并标记为@Measured注释。

要运行它,您需要两个库:字节buddy和byte-buddy-agent。

工作的结果:

void foo(arg0) took 95 ms
void foo(arg1) took 50 ms
void foo(arg2) took 50 ms
void foo(arg3) took 50 ms

请注意,控制台显示传递给方法的所有参数的值。这是对问题的答案。

这是注释示例:

    package md.leonis.shingler;
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface Measured {
    }

说实话,我无法通过代理中的注释直接配置过滤。这是一个示例(不工作(:

    new AgentBuilder.Default()
                    .type(ElementMatchers.isAnnotatedWith(Measured.class))
                    .transform((builder, type, classLoader, module) ->
                            builder.method(ElementMatchers.any()).intercept(MethodDelegation.to(AccessInterceptor.class))
                    ).installOn(instrumentation);

如果有人知道该怎么做,请在下面发表评论。

最新更新