使用ByteBuddy的工具不适用于第三方类

时间:2019-05-23 11:36:25

标签: java instrumentation byte-buddy

当我尝试检测第三方类时,使用ByteBuddy的乐器无法正常工作

我设法创建代码来检测我自己的代码,并且一切都按预期工作。 当我尝试对属于第三方依赖项的类使用相同的代码时,检测无效。

此代码对我有用:

public class A {
    public void print(){
        System.out.println("in class A method 'print'");
    }
}
public class AgentLoad {

    public static void agentmain(String agentArgs, Instrumentation inst) throws Exception {

        final ElementMatcher.Junction<NamedElement> matcher = ElementMatchers.named("com.instrumentation.A");

        new AgentBuilder.Default()
                .type(matcher)
                .transform( new AgentBuilder.Transformer.ForAdvice()
                        .include(AgentLoad.class.getClassLoader())
                        .advice(named("print"), AAdvice.class.getName()))
                .installOn(inst);
    }


  public static void main(String[] args) throws Exception{
      AgentLoader.loadAgentClass(AgentLoad.class.getName(), null);
  }

    public static class AAdvice {

        @Advice.OnMethodEnter
        public static void enter() {
            System.out.println("Enter Yes!!!!");
        }

        @Advice.OnMethodExit
        public static void exit() {
            System.out.println("Exist Yes!!!!");
        }
    }
}

此代码不适用于我:

       public static void agentmain(String agentArgs, Instrumentation inst) {

        AgentBuilder builder = new AgentBuilder.Default();
        builder.type(ElementMatchers.named("com.amazonaws.http.AmazonHttpClient"))
                .transform( new AgentBuilder.Transformer.ForAdvice()
                        .include(AgentLoad.class.getClassLoader())
                        .advice(ElementMatchers.named("execute").and(isAnnotatedWith(SdkInternalApi.class)),
                                AmazonHttpClientAdvice.class.getName()));
        builder.installOn(inst);
    }

    public static class AmazonHttpClientAdvice {

        @Advice.OnMethodEnter
        public static void executeEnter(@Advice.Argument(0) Request<?> request) {
            System.out.println("Eenter !!!" + request);
        }


        @Advice.OnMethodExit
        public static void exit(@Advice.Return(readOnly = false, typing = DYNAMIC) Object returned) {
            System.out.println("Exist !!!! " + returned);
        }
}
    }

预期的结果是在类AmazonHttpClient中调用“ execute”时打印进入和退出。

注意:代理使用下一个库https://github.com/electronicarts/ea-agent-loader

动态附加。

1 个答案:

答案 0 :(得分:0)

Byte Buddy的API是不可变的,所有方法调用都没有副作用,但只会返回一个新的生成器实例。这意味着:

AgentBuilder builder = new AgentBuilder.Default();
builder.type(ElementMatchers.named("com.amazonaws.http.AmazonHttpClient"))
  .transform(new AgentBuilder.Transformer.ForAdvice()
               .include(AgentLoad.class.getClassLoader())
               .advice(ElementMatchers.named("execute").and(isAnnotatedWith(SdkInternalApi.class)),
                       AmazonHttpClientAdvice.class.getName()));
builder.installOn(inst);

不执行任何操作。您需要再次将构建器链的结果重新分配给构建器变量,或在链中调用installOn