How can I achieve this?
public class GenericClass
{
public Type getMyType()
{
//How do I return the type of T?
}
}
Use Guava.
import com.google.common.reflect.TypeToken;
import java.lang.reflect.Type;
public abstract class GenericClass {
private final TypeToken typeToken = new TypeToken(getClass()) { };
private final Type type = typeToken.getType(); // or getRawType() to return Class super T>
public Type getType() {
return type;
}
public static void main(String[] args) {
GenericClass example = new GenericClass() { };
System.out.println(example.getType()); // => class java.lang.String
}
}
A while back, I posted some full-fledge examples including abstract classes and subclasses here.
Note: this requires that you instantiate a subclass of GenericClass
so it can bind the type parameter correctly. Otherwise it'll just return the type as T
.