首页 > 解决方案 > 如何实例化具有带参数的私有构造函数的泛型类

问题描述

我正在使用 3rd-party 库创建一个 java 应用程序,并希望实例化它的类。但是,该类是通用的,只有一个私有构造函数。

我试图通过 Guice 注入创建一个实例。 Test<T>无法修改,因此我既没有使用 @Inject 进行注释,也没有添加非私有的零参数构造函数。

public class Test<T> {
    private final T value;

    private Test(T value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value.toString();
    }
}
Injector injector = Guice.createInjector(new AbstractModule() {
    @Override
    protected void configure() {
        bind(new TypeLiteral<Test<String>>() {
        });
    }
});
Test<String> test = (Test<String>) injector.getInstance(Test.class);
System.out.println(String.format("%s", test));
1) Could not find a suitable constructor in com.example.app.Test. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private.

我想知道如何将参数放入 Test 类的构造函数,以及如何实例化它。

标签: javareflection

解决方案


您可以(但可能不应该)使用反射来做到这一点:

    Constructor<Test> declaredConstructor = Test.class.getDeclaredConstructor(Object.class);
    declaredConstructor.setAccessible(true); // or if (declaredConstructor.trySetAccessible()) on java 9+
    Test<String> obj = declaredConstructor.newInstance("value of first parameter");

泛型在运行时被忽略,因此您只需要在此处使用下限Object.class。如果是这样,class Test<T extends Something>那么您会寻找,Something.class否则默认情况下它是 Object 。

如果该测试类来自某个库,则可能有创建它的方法......所以你可以避免使用反射。


推荐阅读