为什么instanceof运算符允许使用无界通配符类型,但不允许Java中的其他参数化类型? [英] Why is instanceof operator allowed on an unbounded wild card type but not on other parameterized types in Java?

查看:82
本文介绍了为什么instanceof运算符允许使用无界通配符类型,但不允许Java中的其他参数化类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为,由于输入删除,使用 instanceof class literals 不允许用于参数化泛型,除无界通配符类型。为什么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)

这篇关于为什么instanceof运算符允许使用无界通配符类型,但不允许Java中的其他参数化类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆