【发布时间】:2018-01-25 15:23:00
【问题描述】:
有没有办法使用 ByteBuddy 为没有空构造函数的类创建代理?
这个想法是为给定的具体类型创建一个代理,然后将所有方法重定向到一个处理程序。
这个测试展示了为没有空构造函数的类创建代理的场景,它会抛出一个java.lang.NoSuchMethodException
@Test
public void testProxyCreation_NoDefaultConstructor() throws InstantiationException, IllegalAccessException {
// setup
// exercise
Class<?> dynamicType = new ByteBuddy() //
.subclass(FooEntity.class) //
.method(ElementMatchers.named("toString")) //
.intercept(FixedValue.value("Hello World!")) //
.make().load(getClass().getClassLoader()).getLoaded();
// verify
FooEntity newInstance = (FooEntity) dynamicType.newInstance();
Assert.assertThat(newInstance.toString(), Matchers.is("Hello World!"));
}
实体:
public class FooEntity {
private String value;
public FooEntity(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
}
【问题讨论】:
标签: java byte-buddy dynamic-proxy