instanceof - 不兼容的条件操作数类型
以下代码可以正常编译:
Object o = new Object();
System.out.println(o instanceof Cloneable);
但这则不然:
String s = new String();
System.out.println(s instanceof Cloneable);
会抛出编译器错误。
问题是什么?
The following compiles fine:
Object o = new Object();
System.out.println(o instanceof Cloneable);
But this doesn't:
String s = new String();
System.out.println(s instanceof Cloneable);
A compiler error is thrown.
What is the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我最近遇到的一个相关问题(在我弄清楚发生了什么之前,它引导我进入此页面)是,由于以下原因,Eclipse 环境可能会在“instanceof”表达式中错误地报告“不兼容的条件操作数类型”缺少“instanceof”右侧类型的“import”语句。我花了一段时间试图弄清楚有问题的类型如何可能不兼容,然后才发现缺少导入导致了整个问题。希望这些信息可以节省一些时间。
A related issue that I have come across recently (and which led me to this page, before I figured out what was going on) is that the Eclipse environment can report "Incompatible conditional operand types" in an 'instanceof' expression erroneously due to a missing 'import' statement for the type on the right of the 'instanceof'. I spent a while trying to figure out how the types in question could possibly be incompatible before figuring out that a missing import was causing the whole problem. Hopefully this information saves somebody some time.
您的问题的更明显的体现如下:
这是在 JLS 15.20.2 类型比较运算符
instanceof
:也就是说,由于此强制转换表达式会生成编译时错误:
因此此表达式也必须:
您的情况有点微妙,但原理是相同的:
String
是一个最终类String< /code> 没有实现
Cloneable
(Cloneable) aString
aString instanceof Cloneable
A more blatant incarnation of your problem is the following:
This is specified in JLS 15.20.2 Type comparison operator
instanceof
:That is, since this cast expression generates a compile time error:
so must this expression:
Your case is a bit more subtle, but the principle is the same:
String
is a final classString
does not implementCloneable
(Cloneable) aString
aString instanceof Cloneable
编译器知道
String
是最终类,并且不实现Cloneable
。因此,String 的实例永远都不能是Cloneable
的实例。它阻止你认为你已经进行了有意义的测试,而实际上它总是打印“false”。The compiler knows that
String
is a final class and doesn't implementCloneable
. So no instance of String can ever be an instance ofCloneable
. It's stopping you from thinking you've got a meaningful test when actually it will always print "false".