java使用bytebuddy重新定义类
我想重新定义已经在现有框架中定义的源类。我想用我的增强类自动替换源类的原始实例。我无法访问创建源对象的代码,因此类替换必须在后台自动执行。有没有可能使用字节好友来实现这一点
ByteBuddyAgent.install();
Source source = new ByteBuddy()
.subclass(Source.class)
.method(named("hello")).intercept(MethodDelegation.to(Target.class))
.defineMethod("myNewMethod", void.class).intercept(MethodDelegation.to(Target.class))
.make()
.load(Source.class.getClassLoader(),
ClassReloadingStrategy.fromInstalledAgent())
.getLoaded()
.newInstance();
# 1 楼答案
可以使用Byte Buddy重新定义类。为此,可以使用
ByteBuddy::redefine
或ByteBuddy::rebase
方法,而不是子类化。使用这些特性的最规范的方法是为AgentBuilder
定义一个Java代理