ByteBuddy没有重新定义静态方法



我试图重新定义2方法使用ByteBuddy,像这样:

ClassLoader classLoader = ClassLoader.getSystemClassLoader();
ClassLoadingStrategy.Default classLoadingStrategy = ClassLoadingStrategy.Default.INJECTION;
new ByteBuddy().redefine(CommandBase.class).method(returns(Item.class)).intercept(MethodDelegation.to(CppItemInterceptor.class)).make().load(classLoader, classLoadingStrategy);
new ByteBuddy().redefine(CommandBase.class).method(returns(Block.class)).intercept(MethodDelegation.to(CppBlockInterceptor.class)).make().load(classLoader, classLoadingStrategy);
try {
    System.out.println(CppBlockInterceptor.getBlockByText(null, "1").getLocalizedName());
    System.out.println(CommandBase.getBlockByText(null, "1").getLocalizedName());
} catch (Exception e) {
    e.printStackTrace();
}

直接调用CppBlockInterceptor会产生预期的输出,但是调用应该被替换的方法仍然使用旧的行为。这有什么原因吗?

您的CommandBase类在您有机会重新定义它之前已经加载了。Byte Buddy在不使用Java代理的情况下不能替换已加载的类。试着运行这个:

TypeDescription commandBase = new TypePool.Default.ofClassPath()
    .locate("my.package.CommandBase");
new ByteBuddy()
  .redefine(commandBase, ClassFileLocator.ForClassLoader.ofClassPath())
  .method(returns(Block.class)).intercept(MethodDelegation.to(CppBlockInterceptor.class))
  .make()
  .load(ClassLoader.getSystemClassLoader(), ClassLoadingStrategy.Default.INJECTOR);
CppBlockInterceptor.getBlockByText(null, "1").getLocalizedName()

在调用之前没有显式地引用CommandBase,它将工作。不过,更好的方法是使用AgentBuilder和Java代理。Byte Buddy的文档解释了为什么。

接受的答案不再是可编译的(这并不奇怪,因为5年多过去了)。使用Byte Buddy v1.10.17的正确代码如下:

TypeDescription typeDescription = TypePool.Default.ofSystemLoader()
    .describe("my.package.CommandBase")
    .resolve();
new ByteBuddy()
    .redefine(typeDescription, ClassFileLocator.ForClassLoader.ofSystemLoader())
    .method(returns(Block.class)).intercept(MethodDelegation.to(CppBlockInterceptor.class))
    .make()
    .load(ClassLoader.getSystemClassLoader(), ClassLoadingStrategy.Default.INJECTION);

最新更新