Cannot perform instanceof check against parameterized type ArrayList<Foo>

匿名 (未验证) 提交于 2019-12-03 01:33:01

问题:

The following code:

((tempVar instanceof ArrayList) ? tempVar : null); 

causes:

Cannot perform instanceof check against parameterized type ArrayList. 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?

回答1:

It means that if you have anything that is parameterized, e.g. List fooList = new ArrayList();, 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. You can "store" the parameterized type explicitly and do a comparison there.



回答2:

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(); } 


回答3:

Due to type erasure, the parameterized type of the ArrayList won't be known at runtime. The best you can do with instanceof is to check whether tempVar is an ArrayList (of anything). To do this in a generics-friendly way, use:

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


回答4:

This is sufficient:

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 NullPointerException.



回答5:

You can't fix that. The type information for Generics is not available at runtime and you won't have access to it. You can only check the content of the array.



回答6:

instanceof operator works at runtime. But java does not carry the parametrized type info at runtime. They are erased at compile time. Hence the error.



回答7:

You could always do this

Create a class

public class ListFoo {   private List theList;    public ListFoo(List theList {     this.theList = theLista;   }    public List getList() {     return theList;   } } 

Is not the same but ...

myList = new ArrayList; ..... Object tempVar = new ListFoo(myList); .... ((tempVar instanceof ListFoo) ? tempVar.getList() : null); 


回答8:

You can use

boolean isInstanceArrayList = tempVar.getClass() == ArrayList.class 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!