简体   繁体   中英

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

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:

  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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM