mardi 3 septembre 2019

How to instantiate generic class which has a private constructor with an argument

I'm creating a java application with 3rd-party library, and want to instantiate its class. However, the class is generic and only has a private constructor.

I've tried to create an instance by Guice injection. Test<T> can't be modified, so I did neither annotate with @Inject nor add a zero-argument constructor that is not private.

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.

I want to know how can I put an argument to the constructor of Test class, and how to instantiate it.





Aucun commentaire:

Enregistrer un commentaire