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?
If those are actually fields of a certain class, then you can get them with a little help of reflection:
You can also do that for parameter types and return type of methods.
But if they're inside the same scope of the class/method where you need to know about them, then there's no point of knowing them, because you already have declared them yourself.
Expanding on Steve K's answer:
Had the same problem, but I used instanceof instead. Did it this way:
This involves using unchecked casts so only do this when you know it is a list, and what type it can be.
Use Reflection to get the
Field
for these then you can just do:field.genericType
to get the type that contains the information about generic as well.Short answer: no.
This is probably a duplicate, can't find an appropriate one right now.
Java uses something called type erasure, which means at runtime both objects are equivalent. The compiler knows the lists contain integers or strings, and as such can maintain a type safe environment. This information is lost (on an object instance basis) at runtime, and the list only contain 'Objects'.
You CAN find out a little about the class, what types it might be parametrized by, but normally this is just anything that extends "Object", i.e. anything. If you define a type as
AClass.class will only contain the fact that the parameter A is bounded by MyClass, but more than that, there's no way to tell.