可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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