Unable to perform instance validation with parameterized type ArrayList <Foo>
The following code:
((tempVar instanceof ArrayList<Foo>) ? tempVar : null); causes:
Cannot perform
instanceofvalidation with a parameterized typeArrayList<Foo>. Use theArrayList<?>Form, since additional type information will be deleted at runtime
Can someone explain to me what is meant by "additional information of a general type that will be erased at runtime" and how to fix it?
This means that if you have something that is parameterized, for example. List<Foo> fooList = new ArrayList<Foo>(); , Generics information will be deleted at runtime. Instead, it will see the JVM List fooList = new ArrayList(); .
This is called type erasure . The JVM does not have parameterized List type information (in the example) at run time.
To fix? Since the JVM does not have parameterized type information at run time, you cannot make instanceof from ArrayList<Foo> . You can "save" the parameterized type explicitly and do a comparison there.
You can always do this instead.
try { if(obj instanceof ArrayList<?>) { if(((ArrayList<?>)obj).get(0) instanceof MyObject) { // do stuff } } } catch(NullPointerException e) { e.printStackTrace(); } Due to type erasure, the parameterized type ArrayList will not be known at run time. The best you can do with instanceof is to check if tempVar ArrayList (anything). To make this a universal way, use:
((tempVar instanceof ArrayList<?>) ? tempVar : null); It's enough:
if(obj instanceof ArrayList<?>) { if(((ArrayList<?>)obj).get(0) instanceof MyObject) { // do stuff } } In fact, instanceof checks whether the left operand is null or not, and returns false if it is actually null .
So: no need to catch a NullPointerException .
You cannot fix it. Generics type information is not available at runtime and you will not have access to it. You can only check the contents of the array.
works at runtime. But java does not carry parameterized type information at runtime. They are erased during compilation. Hence the error.
You can always do it
Create class
public class ListFoo { private List<Foo> theList; public ListFoo(List<Foo> theList { this.theList = theLista; } public List<Foo> getList() { return theList; } } Not the same, but ...
myList = new ArrayList<Foo>; ..... Object tempVar = new ListFoo(myList); .... ((tempVar instanceof ListFoo) ? tempVar.getList() : null); you can use
boolean isInstanceArrayList = tempVar.getClass() == ArrayList.class