I have a list like that:
private List<T> myList = new ArrayList<T>();
I want to get the .class of T. How can I do that?
I mean as like:
myList.getClass()
EDIT: I tried that:
Field genericField = Wrapper.class.getDeclaredField("myList");
ParameterizedType genericType = (ParameterizedType) genericField.getGenericType();
Class<?> genericClass = (Class<?>) genericType.getActualTypeArguments()[0];
and when I debug it
genericType
has a value of:
java.util.List
so I think that this is certainly different issue from that question: Get generic type of java.util.List because of if you declare a class with T
and assign something to T
later at another method, class that T
holds disappear.
Why do you need to know this? Perhaps this will do what you need
The only way to do this is to either
like
like
This has the dis-advantage that you could end up creating lots of anonymous classes and potential confusion with things like
ArrayList.class != list.getClass()
howeverlist instanceof ArrayList
This is only possible if the list, as implied in your example, is a field AND the type parameter is concrete rather than itself being a type parameter of the enclosing class (which seems to be the case in your example), and you can only get the declared type parameter for the field via reflection:
Not sure if this is entirely correct, but you get the idea - it's rather complex because type parameters can be bounded and wildcards.
You can't because of type erasure. The generic type is not known at runtime (it's 'erased'), it's only used at compile time.
This is a major difference between java generics and c# generics for example.
You cannot. That information is not available at runtime. If your list isn't empty you might be able to get away with checking the class of the first element.