不能执行的instanceof对证参数化类型的ArrayList<富>参数、类型、instanceof、GT

2023-09-06 00:30:50 作者:顾北

下面code:

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

原因:

无法执行的instanceof 核对参数化类型的ArrayList&LT;富&GT; 。可以用的ArrayList&LT;&GT; 替代,因为进一步的泛型类型信息将在运行时被删除

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

推荐答案

这意味着,如果你有任何的参数,例如: 名单,其中,富&GT; fooList =新的ArrayList&LT;富&GT;(); 的泛型信息将在运行时被删除。相反,这是JVM将看到列表fooList =新的ArrayList();

It means that if you have anything that is parameterized, e.g. List<Foo> fooList = new ArrayList<Foo>();, the Generics information will be erased at runtime. Instead, this is what the JVM will see List fooList = new ArrayList();.

这被称为类型擦除。在JVM具有列表运行期间没有参数化类型信息(本例中)。

This is called type erasure. The JVM has no parameterized type information of the List (in the example) during runtime.

一个修复?由于JVM有参数化类型上运行的任何信息,也没有办法,你可以做一个的instanceof 的ArrayList的&LT;富&GT; 。你可以在商店的参数明确的类型,做一个比较有。

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<Foo>. You can "store" the parameterized type explicitly and do a comparison there.