Java generics - get class? [duplicate]
I got a list, programmed like this: public class MyList<T>
. Is there any way to use the T variable to get the name of class (so I can, from within MyList
, know if T is String, Socket, etc.)?
EDIT: Nevermind, found the answer here.
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];
}
...
You are seeing the result of Type Erasure. From that page...
When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. Type erasure enables Java applications that use generics to maintain binary compatibility with Java libraries and applications that were created before generics.
For instance, Box<String> is translated to type Box, which is called the raw type — a raw type is a generic class or interface name without any type arguments. This means that you can't find out what type of Object a generic class is using at runtime.
This also looks like this question which has a pretty good answer as well.