mardi 21 mars 2017

instanciate generic Parameter of a class

I have a class

class Holder<SomeType extends AbstractType>{
    SomeType createType(){...}
}

then outside of it, I call

Holder holder = new Holder<MyType>();

I can't figure out how to implements the createType() method.

I tried about everything I could find in StackOverFlow and the web, but I always run in the same dead end : At runtime if I do

TypeVariable typeVariable = getClass().getTypeParameters()[0];
System.err.println("typeVariable "+typeVariable);

I get "SomeType" instead of "MyType", and so I can't fetch the appropriate Constructor since I want to use Class.forName("MyType") and not Class.forName("SomeType") which lead to a java.lang.ClassNotFoundException

I use SomeType extends AbstractType, so I known all my MyTypes will have the same constructor available.

I can't use

ParameterizedType t = (ParameterizedType) MyClass.class.getGenericSuperclass();

since Holder is not a Subclass of anything usefull

I could do something like this in my Holder class, but i'm looking for a way to use reflection without having to pass an argument in the Constructor

private final Class<SomeType> type;

public Holder(Class<SomeType> type) {
    this.type = type;
}

Trying all the various ideas I saw on the net fells like I'm chasing my tail, so I guess I'm missing an obvious element here.

Thanks for your help !





Aucun commentaire:

Enregistrer un commentaire