简体   繁体   English

当类只有一个私有构造函数时,如何创建代理?

[英]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. 我想使用ByteBuddy为具有私有构造函数的类创建代理。 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. 不允许调用私有构造函数的Java字节码真的无法做任何事情。 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. 使用ByteBuddy::redefine添加另一个构造函数,并使用代理或过早加载将此类强制装入类加载器。
  2. Use a library like Objenesis to create an instance without calling a constructor. 使用Objenesis之类的库来创建实例,而无需调用构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何访问 class 的私有构造函数? - How can I access a private constructor of a class? 如何使用反射创建具有私有字段和构造函数的类对象? - How can I make an object of class having private fields and constructor using reflection? 如何在具有私有构造函数的本地内部类的外部创建实例? - How is it possible to create instance outside class of local inner class having private constructor? 最佳实践:为仅具有静态方法的类创建私有构造函数 - Best Practice : Creating private constructor for a class having only static methods 如何在具有私有构造函数的 class 中使用 @Value 或 autowire 环境? - How can I use @Value or autowire Environment in a class with private constructor? 如何使用私有构造函数从类创建对象? - How to create objects from a class with private constructor? 如何使用包私有构造函数创建类? - How to create a class with a package private constructor? 如何创建可以组成一个以上类的方法的代理? - How to create a Proxy that can compose methods of more than one class? 在Java中,我们可以在一个类中创建多少个构造函数? - In Java how many constructor can we create in one class? 如何在不调用此类的构造函数的情况下创建类的实例? - How can I create an instance of class without invoking constructor of this class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM