-1
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?

Eran
  • 387,369
  • 54
  • 702
  • 768
electron
  • 801
  • 8
  • 18

5 Answers5

2

You cant get it in runtime. In runtime its just ArrayList<Object>

DontRelaX
  • 744
  • 4
  • 10
2

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
2

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

You can't - generic type information is erased at runtime.

Smutje
  • 17,733
  • 4
  • 24
  • 41
1

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.
SMA
  • 36,381
  • 8
  • 49
  • 73
  • thanks but list may be empty and too many type may be passed as type argument. – electron Nov 28 '14 at 10:32
  • You will need an element at least to figure out what type of element you entered in your list. Else i don't think you will be able to figure out the type as type information is erased at run time. – SMA Nov 28 '14 at 10:40