I have;
List<String> stringList = new ArrayList<String>();
List<Integer> integerList = new ArrayList<Integer>();
Is there a (easy) way to retrieve the generic type of the list?
I have;
List<String> stringList = new ArrayList<String>();
List<Integer> integerList = new ArrayList<Integer>();
Is there a (easy) way to retrieve the generic type of the list?
Generally impossible, because
List<String>
andList<Integer>
share the same runtime class.You might be able to reflect on the declared type of the field holding the list, though (if the declared type does not itself refer to a type parameter whose value you don't know).
At runtime, no, you can't.
However via reflection the type parameters are accessible. Try
The method
getGenericType()
returns a Type object. In this case, it will be an instance ofParametrizedType
, which in turn has methodsgetRawType()
(which will containList.class
, in this case) andgetActualTypeArguments()
, which will return an array (in this case, of length one, containing eitherString.class
orInteger.class
).If you need to get the generic type of a returned type, I used this approach when I needed to find methods in a class which returned a
Collection
and then access their generic types:This outputs:
As others have said, the only correct answer is no, the type has been erased.
If the list has a non-zero number of elements, you could investigate the type of the first element ( using it's getClass method, for instance ). That won't tell you the generic type of the list, but it would be reasonable to assume that the generic type was some superclass of the types in the list.
I wouldn't advocate the approach, but in a bind it might be useful.
For finding generic type of one field:
The generic type of a collection should only matter if it actually has objects in it, right? So isn't it easier to just do:
There's no such thing as a generic type in runtime, but the objects inside at runtime are guaranteed to be the same type as the declared generic, so it's easy enough just to test the item's class before we process it.