instanceof - 不兼容的条件操作数类型 [英] instanceof - incompatible conditional operand types
问题描述
以下编译正常:
Object o = new Object();
System.out.println(o instanceof Cloneable);
但这不是:
String s = new String();
System.out.println(s instanceof Cloneable);
抛出编译器错误。
问题是什么?
推荐答案
您问题的更明确的表现如下:
A more blatant incarnation of your problem is the following:
if ("foo" instanceof Number)
// "Incompatible conditional operand types String and Number"
这在 JLS 15.20.2类型比较运算符 instanceof
:
RelationalExpression:
RelationalExpression instanceof ReferenceType
如果将 RelationalExpression 转换为 ReferenceType 作为编译时错误而被拒绝,那么 instanceof
关系表达式同样会产生编译时错误。在这种情况下, instanceof
表达式的结果永远不会为真。
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. In such a situation, the result of the instanceof
expression could never be true.
也就是说,因为这个强制转换表达式会产生编译时错误:
That is, since this cast expression generates a compile time error:
(Number) "foo"
所以必须这个表达式:
("foo" instanceof Number)
你的情况有点微妙,但原理是一样的:
Your case is a bit more subtle, but the principle is the same:
-
String
是最终类 -
字符串
未实现Cloneable
- 因此你不能做
(Cloneable)aString
- 所以你也做不到
aString instanceof Cloneable
String
is a final classString
does not implementCloneable
- Therefore you can't do
(Cloneable) aString
- Therefore also you can't do
aString instanceof Cloneable
这篇关于instanceof - 不兼容的条件操作数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!