The following code:
((tempVar instanceof ArrayList<Foo>) ? tempVar : null);
causes:
Cannot perform
instanceof
check against parameterized typeArrayList<Foo>
. Use the formArrayList<?>
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?
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.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With