无法对参数化typesArrayList <Foo>执行instanceof检查
以下代码:
((tempVar instanceof ArrayList<Foo>) ? tempVar : null); 原因:
无法对参数化types
ArrayList<Foo>执行instanceof检查。 请使用表单ArrayList<?>因为更多的genericstypes信息将在运行时被删除
有人可以解释我什么是“进一步genericstypes信息将被删除在运行时”以及如何解决这个问题?
 这意味着如果你有任何参数化的,例如List<Foo> fooList = new ArrayList<Foo>();  ,generics信息将在运行时被删除。 相反,这是JVM将看到的List fooList = new ArrayList();  。 
 这被称为types删除 。  JVM在运行时没有List参数化types信息(在这个例子中)。 
 修复? 由于JVM在运行时没有参数化types的信息,因此您无法执行ArrayList<Foo>的instanceof 。 你可以显式地“存储”参数化types,并在那里进行比较。 
你可以一直这样做
 try { if(obj instanceof ArrayList<?>) { if(((ArrayList<?>)obj).get(0) instanceof MyObject) { // do stuff } } } catch(NullPointerException e) { e.printStackTrace(); } 
 由于types擦除, ArrayList的参数化types在运行时不会被知道。 使用instanceof可以做的最好的事情是检查tempVar是否是ArrayList (任何东西)。 要以通用的方式执行此操作,请使用: 
 ((tempVar instanceof ArrayList<?>) ? tempVar : null); 
这已经足够了:
 if(obj instanceof ArrayList<?>) { if(((ArrayList<?>)obj).get(0) instanceof MyObject) { // do stuff } } 
 实际上, instanceof检查左操作数是否为null ,如果实际为null ,则返回false 。 
 所以:不需要捕获NullPointerException 。 
你不能解决这个问题。 generics的types信息在运行时不可用,您将无法访问它。 你只能检查数组的内容。
instanceof操作符在运行时工作。 但是java不会在运行时携带参数化types信息。 它们在编译时被擦除。 因此,错误。
你总是可以做到这一点
创build一个class级
 public class ListFoo { private List<Foo> theList; public ListFoo(List<Foo> theList { this.theList = theLista; } public List<Foo> getList() { return theList; } } 
不一样,但…
 myList = new ArrayList<Foo>; ..... Object tempVar = new ListFoo(myList); .... ((tempVar instanceof ListFoo) ? tempVar.getList() : null); 
您可以使用
 boolean isInstanceArrayList = tempVar.getClass() == ArrayList.class