【问题标题】:ByteBuddy MethodDelegation not working in Java AgentByteBuddy MethodDelegation 在 Java 代理中不起作用
【发布时间】:2017-03-02 15:06:19
【问题描述】:

我有一个 premain() ,其中所有使用某个注释注释的方法都应该委托给某个类。一般来说,我看起来像这样:

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);
}

使用调试器显示这部分已被处理,但如果调用了带注释的方法,则没有任何反应。

CountingInterception 看起来像这样

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();
  }
}

感谢任何提示!

使用 ByteBuddy 1.6.9

【问题讨论】:

    标签: java byte-buddy


    【解决方案1】:

    为了实现我想要做的,进行了以下更改:

    在主目录中:

    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);
    

    在 CountingInterception 中:

    public void interceptor(@Origin final Method method) throws Exception {
    
        String name = method.getAnnotation(Counted.class).name();
        if (name != null) {
          // do something
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      我假设您正在尝试做一些不同于 Java 8 默认方法调用的事情。您的意思是使用调用超级方法的@SuperCall 吗?

      我建议您: 1.减少你的拦截器什么都不做。创建一个拦截器,将MethodDelegationSuperMethodCall 链接起来。 2.注册AgentBuilder.Listener,将错误写入控制台。

      我确信 Byte Buddy 无法绑定您的方法,因为您的拦截器只能应用于提供默认方法实现的类。

      【讨论】:

      • 感谢您的提示。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多