Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot perform instanceof check against parameterized type ArrayList<Foo>

The following code:

((tempVar instanceof ArrayList<Foo>) ? tempVar : null); 

causes:

Cannot perform instanceof check against parameterized type ArrayList<Foo>. Use the form ArrayList<?> instead since further generic type information will be erased at runtime

Can someone explain me what is meant by "further generic type information will be erased at runtime" and how to fix this?

like image 995
Caner Avatar asked Sep 07 '11 13:09

Caner


2 Answers

It means that if you have anything that is parameterized, e.g. List<Foo> fooList = new ArrayList<Foo>();, the Generics information will be erased at runtime. Instead, this is what the JVM will see List fooList = new ArrayList();.

This is called type erasure. The JVM has no parameterized type information of the List (in the example) during runtime.

A fix? Since the JVM has no information of the Parameterized type on runtime, there's no way you can do an instanceof of ArrayList<Foo>. You can "store" the parameterized type explicitly and do a comparison there.

like image 110
Buhake Sindi Avatar answered Oct 08 '22 19:10

Buhake Sindi


You could always do this instead

try {     if(obj instanceof ArrayList<?>)     {         if(((ArrayList<?>)obj).get(0) instanceof MyObject)         {             // do stuff         }     } } catch(NullPointerException e) {     e.printStackTrace(); } 
like image 24
Greg Avatar answered Oct 08 '22 20:10

Greg