为什么instanceof运算符允许使用无界通配符类型,但不允许Java中的其他参数化类型?
我认为,由于输入删除,使用 instanceof
和 class literals
不允许用于参数化泛型$ c>,除无界通配符类型
。为什么Java语言设计者允许这种异常?对于无界通配符类型,没有类型擦除的作用?
I think due to type erasure , using instanceof
and class literals
are not allowed for parameterized generic types
except unbounded wild card types
. Why did the Java language designers allowed this exception ? There isn't any role of type erasure for unbounded wild card types ?
关键是对象知道它的具体类 - 但不是泛型类型的参数。所以如果我们构造一个 ArrayList< Integer>
,它知道在执行时它是一些 ArrayList
kind - 但它不知道整数
部分。
The point is that an object knows its concrete class - but not the generic type arguments for that. So if we construct an ArrayList<Integer>
, that knows at execution time that it's an ArrayList
of some kind - but it doesn't know about the Integer
part.
ArrayList
某种部分恰恰是 ArrayList
的意思,这就是为什么:
The "ArrayList
of some kind" part is precisely what ArrayList<?>
means, which is why:
if (foo instanceof ArrayList<?>)
有效。这与使用原始类型相同:
is valid. It's just equivalent to using the raw type:
if (foo instanceof ArrayList)