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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.