Java generics - get class?
Short answer: You can't.
Long answer:
Due to the way generics is implemented in Java, the generic type T is not kept at runtime. Still, you can use a private data member:
public class Foo<T>
{
private Class<T> type;
public Foo(Class<T> type) { this.type = type; }
}
Usage example:
Foo<Integer> test = new Foo<Integer>(Integer.class);
I like the solution from
http://www.nautsch.net/2008/10/28/class-von-type-parameter-java-generics/
public class Dada<T> {
private Class<T> typeOfT;
@SuppressWarnings("unchecked")
public Dada() {
this.typeOfT = (Class<T>)
((ParameterizedType)getClass()
.getGenericSuperclass())
.getActualTypeArguments()[0];
}
...