gpt4 book ai didi

java - 重新定义非静态方法

转载 作者:行者123 更新时间:2023-12-03 20:24:56 26 4
gpt4 key购买 nike

我尝试重新定义简单的非静态方法,但出现异常:

Exception in thread "main" java.lang.UnsupportedOperationException: class redefinition failed: attempted to change the schema (add/remove fields)

类:

class Source { 
def hello(name: String): String = ""
}

class Target {
def hello(name: String): String = "Hello" + name + "!"
}

调用:

 new ByteBuddy()
.rebase(classOf[Source])
.method(ElementMatchers.named("hello"))
.intercept(MethodDelegation.to(new Target))
.make()
.load(classOf[Source].getClassLoader, ClassReloadingStrategy.fromInstalledAgent())
.getLoaded
.newInstance()
.hello("World")

上面的类是 scala 类,但它们编译为标准的 java 类。

如何正确重定义方法?

最佳答案

JVM 当前不支持您尝试执行的操作,您不能在任何类中添加或删除字段或方法,这是 rebase 的隐含结果。

您可以做的是使用 ByteBuddy::redefine 重新定义一个类。这样,Byte Buddy 替换了原始实现,而不是保留它以供潜在调用。为了完成这项工作,您还需要委托(delegate)给一个无状态(startic)方法,如下所示:

public class Target {
public static String hello() {
return "Hello" + name + "!"
}
}

使用委托(delegate):MethodDelegation.to(Target.class)。这是必要的,因为否则,Byte Buddy 将需要向检测类添加一个字段来存储委托(delegate)实例,而重新定义是不可能的。

或者,查看 Advice 类,它允许您在保留原始实现的情况下内联与 rebase 兼容的代码。

关于java - 重新定义非静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46318305/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com