Unable to perform instance validation with parameterized type ArrayList <Foo>

The following code:

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

causes:

Cannot perform instanceof validation with a parameterized type ArrayList<Foo> . Use the ArrayList<?> 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?

+42
java android generics
Sep 07 2018-11-11T00:
source share
8 answers

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.

+45
Sep 07 '11 at 1:55 april
source share

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(); } 
+22
Mar 10 '14 at 22:51
source share

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); 
+10
Sep 07 '11 at 1:55 april
source share

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 .

+2
Feb 18 '16 at 17:04
source share

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.

+1
Sep 07 '11 at 1:55 april
source share
Instance operator

works at runtime. But java does not carry parameterized type information at runtime. They are erased during compilation. Hence the error.

+1
Sep 07 2018-11-11T00:
source share

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); 
0
Jan 08 '16 at 19:13
source share

you can use

 boolean isInstanceArrayList = tempVar.getClass() == ArrayList.class 
0
May 18 '16 at 3:14
source share



All Articles