How can I create a proxy when the class having only one private constructor?

329 views Asked by At

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();
    }
}
1

There are 1 answers

0
Rafael Winterhalter On BEST ANSWER

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:

  1. Use ByteBuddy::redefine to add another constructor and either use an agent or premature loading to force this class into your class loader.
  2. Use a library like Objenesis to create an instance without calling a constructor.