[英]ByteBuddy not redefining static method
我正在嘗試使用 ByteBuddy 重新定義 2 種方法,如下所示:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.