public void X(ArrayList list)
{
//reflection code will be here.
}
Let's say list
variable is a type of ArrayList<String>
. How can I get String
(or whatever passed) information with java runtime reflection?
public void X(ArrayList list)
{
//reflection code will be here.
}
Let's say list
variable is a type of ArrayList<String>
. How can I get String
(or whatever passed) information with java runtime reflection?
You can't do that, since the compiler erases the generic type parameters. In runtime all types are raw.
You can test the type of individual elements in the list instead, but there is no guarantee they would all be of the same type.
You can't. This is due to type erasure which happens during compilation. All the runtime sees is ArrayList<java.lang.Object>
.
In this respect, Java Generics are a poor cousin of C++ templates.
You can't get it directly at runtime. Indirectly you could do something like below to get class information about the object you stored:
Class clazz = strList.get(0).getClass();
Provided you defined it like
List<String> strList = new ArrayList<String>();
and added very first element like
strList.add("abc");
Alternatively if you are trying to store different type of data within same list, you will need to iterate over each and every element and do the type checking like
if (strList.get(0) instanceOf String) {
//blah blah
} else if (strList.get(0) instanceOf Integer) {
//blah
}//etc etc.