Using ByteBuddy, I'd like to create a proxy for a class which has a private constructor. That's the class:
public class Foo {
private Foo() {
}
}
I tried write some code like this but not work?
public class CreateAndExecuteProxy {
public static void main(String[] args) throws Exception {
Constructor<?> superConstructor = Foo.class.getDeclaredConstructor();
Class<? extends Foo> proxyType = new ByteBuddy()
.subclass( Foo.class, ConstructorStrategy.Default.NO_CONSTRUCTORS )
.defineConstructor( Visibility.PUBLIC )
.intercept( MethodCall.invoke( superConstructor ).onSuper() )
.make()
.load( CreateAndExecuteProxy.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
.getLoaded();
Foo foo = proxyType.newInstance();
}
}
There is nothing really you can do with Java byte code which does not permit calling a private constructor. There are two options you have:
ByteBuddy::redefine
to add another constructor and either use an agent or premature loading to force this class into your class loader.