[英]instanceof - incompatible conditional operand types
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? 问题是什么?
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'. 我最近遇到的一个相关问题(在我弄清楚发生了什么之前,导致我进入了此页面)是,由于环境错误,Eclipse环境可能错误地在“ instanceof”表达式中报告“不兼容的条件操作数类型”缺少“ instanceof”右侧类型的“ import”语句。 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. 希望这些信息可以节省一些时间。
A more blatant incarnation of your problem is the following: 以下是您的问题的一个更为公然的化身:
if ("foo" instanceof Number)
// "Incompatible conditional operand types String and Number"
This is specified in JLS 15.20.2 Type comparison operator instanceof
: 这在JLS 15.20.2类型比较运算符instanceof
指定:
RelationalExpression: RelationalExpression instanceof ReferenceType
If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the
instanceof
relational expression likewise produces a compile-time error. 如果将RelationalExpression强制转换为ReferenceType作为编译时错误,则关系表达式的instanceof
同样会产生编译时错误。 In such a situation, the result of theinstanceof
expression could never be true. 在这种情况下,instanceof
表达式的结果永远不可能为真。
That is, since this cast expression generates a compile time error: 也就是说,由于此强制转换表达式会产生编译时错误:
(Number) "foo"
so must this expression: 因此,此表达式必须:
("foo" instanceof Number)
Your case is a bit more subtle, but the principle is the same: 您的情况有些微妙,但原理是相同的:
String
is a final class String
是最后一堂课 String
does not implement Cloneable
String
未实现Cloneable
(Cloneable) aString
因此,您不能(Cloneable) aString
aString instanceof Cloneable
因此,你也不能做一个aString instanceof Cloneable
The compiler knows that String
is a final class and doesn't implement Cloneable
. 编译器知道String
是最终类,并且不实现Cloneable
。 So no instance of String can ever be an instance of Cloneable
. 因此,String的任何实例都不能成为Cloneable
的实例。 It's stopping you from thinking you've got a meaningful test when actually it will always print "false". 它实际上使您始终认为“ false”时,您就无法想到您已经进行了有意义的测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.