问题描述
是否可以使用Byte Buddy重新定义类的私有方法?似乎使用Byte Buddy的入口点总是对现有类进行子类化。这样做时,显然不可能重新定义父类的私有方法(至少不能在父类中使用重新定义的方法)。
Is it possible to use Byte Buddy to redefine a private method of a class? It seems that the entry point into using Byte Buddy is always sub-classing an existing class. When doing this, it is obviously not possible to redefine a private method of the parent class (at least not in a way that the redefined method is used in the parent class).
考虑以下示例:
public class Foo {
public void sayHello() {
System.out.println(getHello());
}
private String getHello() {
return "Hello World!";
}
}
Foo foo = new ByteBuddy()
.subclass(Foo.class)
.method(named("getHello")).intercept(FixedValue.value("Byte Buddy!"))
.make()
.load(Main.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded()
.newInstance();
foo.sayHello();
输出为Hello World!。有没有机会得到Byte Buddy!作为输出?
The output will be "Hello World!". Is there any chance to get "Byte Buddy!" as output?
推荐答案
您认为子类化是目前使用Byte Buddy创建类的唯一选项。但是,从下一周发布的0.3版本开始,这将更改,以便您还可以重新定义现有类。类重新定义将如下所示:
You are correct that subclassing is the currently only option for creating classes with Byte Buddy. However, starting with version 0.3 which is released in the next weeks, this will change such that you can also redefine existing classes. A class redefition would then look like this:
ClassReloadingStrategy classReloadingStrategy = ClassReloadingStrategy
.fromInstalledAgent();
new ByteBuddy()
.redefine(Foo.class)
.method(named("getHello"))
.intercept(FixedValue.value("Byte Buddy!"))
.make()
.load(Foo.class.getClassLoader(), classReloadingStrategy);
assertThat(foo.getHello(), is("Byte Buddy!"));
classReloadingStrategy.reset(Foo.class);
assertThat(foo.getHello(), is("Hello World"));
这种方法利用了HotSpot的HotSwap机制,由于无法添加方法或字段,因此机制非常有限。使用Byte Buddy版本0.4,Byte Buddy将能够重新定义卸载的类并提供用于实现自定义Java代理的代理构建器,以使这种重新定义更加灵活。
This approach makes use of HotSpot's HotSwap mechanism which is very limited as you cannot add methods or fields. With Byte Buddy version 0.4, Byte Buddy will be able to redefine unloaded classes and provide an agent builder for implementing custom Java Agents to make this sort of redefinition more flexible.
这篇关于我可以使用Byte Buddy重新定义私有方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!