Is there a way to create a proxy for a class with no empty constructor using ByteBuddy?
The idea is to create a proxy for a given concrete type and then redirect all the methods to a handler.
This test showcases the scenario of creation of a proxy for a clas with no empty constructor and it throws a 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!"));
}
The entity:
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;
}
}