无法在字节好友拦截器中获取方法

问题描述

当我添加

@Origin Method method

到我的拦截器:

@RuntimeType
  public static void intercept(
      @Origin Method method,@RuntimeType @AllArguments Object[] allArguments) {
    System.out.println("intercepted with args: " + Arrays.toString(allArguments));
    System.out.println("intercepted method: " + method);
  }

我以一个例外结束:

Error invoking java.lang.instrument.Instrumentation#retransformClasses
class redeFinition Failed: attempted to change the schema (add/remove fields)

我的设置如下:

ByteBuddyAgent.install();
    final ByteBuddy byteBuddy = new ByteBuddy();

    byteBuddy
        .redefine(ByteBuddyFoo.class)
        .method(ElementMatchers.named("anotherMethod").or(ElementMatchers.named("toString")))
        .intercept(MethodDelegation.to(MethodInterceptor.class))
        .make()
        .load(ByteBuddyFoo.class.getClassLoader(),ClassReloadingStrategy.fromInstalledAgent());

我的简单 POJO 是:

public class ByteBuddyFoo {
  @Override
  public String toString() {
    return "ByteBuddyFoo{}";
  }

  public void anotherMethod(final String input) {
    System.out.println("input from anotherMethod: " + input);
  }
}

当我的拦截器中没有@Origin Method 方法时,它拦截调用就好了;但是,一旦我将其添加回来,它就会抛出上述异常。

我希望能够拦截任何我想要的方法调用,并且可以访问方法、它的参数和结果。最初,我是通过 AspectJ 来做这件事的;但是,我希望能够在运行时执行此操作,因此无需修改我的代码

解决方法

您需要像这样禁用 Method 实例的缓存:

@Origin(cached = false)

为此,但这使得调用相当昂贵。如果您只想将方法实例字符串化,而不是使用 @Origin String method,它无论如何都不需要缓存

重新定义时,应使用.disableClassFormatChanges()