jeudi 29 janvier 2015

Java - Get Interface Generic Type


I'm trying to create an Interface with Generics which allows me to get the type of object in the generics but no matter what I try there's a syntax error. I've tried the following 3 methods.


All of the following code is and MUST be inside an interface with the generics <T extends Bar> and I would rather the method getType() be default but it doesn't have to be.



public interface Foo<T extends Bar> {

public default Class<T> getType1() {
return T.class;
}

public default T getType2() {
return T;
}

public default T getType3() {
return new T();
}
}


1st method gives Error: Cannot select from a type variable

2nd method gives Error: Expression Expected

3rd method gives Error: Type parameter 'T' cannot be instantiated directly.


So if I had two classes that extend Bar, let's just call them BarA and BarB, how can I make a method to figure out if the generic type is BarA or BarB?





Aucun commentaire:

Enregistrer un commentaire