简体   繁体   中英

ByteBuddy MethodDelegation not working in Java Agent

I have a premain() wherein all methods annotated with a certain annotation should be delegated to a certain class. In general, i looks like this:

public static void premain( final String agentArguments, final Instrumentation instrumentation ) {

  CountingInterception ci = new CountingInterception();

  new AgentBuilder.Default()
    .type(ElementMatchers.isAnnotatedWith(com.codahale.metrics.annotation.Counted.class))
      .transform((builder, type, classLoader, module) ->
         builder.method(ElementMatchers.any())
                .intercept(MethodDelegation.to(ci))
      ).installOn(instrumentation);
}

Using a debugger shows that this part is processed but if an annotated method is called, nothing happens.

The CountingInterception looks like this

public class CountingInterception {

  @RuntimeType
  public Object intercept(@DefaultCall final Callable<?> zuper, @Origin final Method method, @AllArguments final Object... args) throws Exception {

    String name = method.getAnnotation(Counted.class).name();
    if (name != null) {
        // do something
    }

    return zuper.call();
  }
}

Thanks for any hints!

Using ByteBuddy 1.6.9

To achieve what I wanted to do, the following changes were made:

In premain:

CountingInterception ci = new CountingInterception();

new AgentBuilder.Default()
    .type(declaresMethod(isAnnotatedWith(Counted.class)))
      .transform((builder, type, classLoader, module) -> builder
        .method(isAnnotatedWith(Counted.class))
                 .intercept(MethodDelegation.to(ci).andThen(SuperMethodCall.INSTANCE))
      ).installOn(instrumentation);

and in CountingInterception:

public void interceptor(@Origin final Method method) throws Exception {

    String name = method.getAnnotation(Counted.class).name();
    if (name != null) {
      // do something
    }

}

I assume that you are trying to do something different than a Java 8 default method call. Did you mean to use @SuperCall which invokes a super method?

I would suggest you to: 1. Reduce your interceptor to do nothing. Create an interceptor that chains your MethodDelegation with a SuperMethodCall . 2. Register an AgentBuilder.Listener to write errors to the console.

I am sure Byte Buddy cannot bind your methods as your interceptor can only be applied to classes that offer a default method implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM