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);
抛出编译器错误.
有什么问题?
您的问题的一个更明显的化身如下:
if ("foo" instanceof Number)//不兼容的条件操作数类型字符串和数字"
这是在 JLS 15.20.2 中指定的类型比较运算符instanceof
:
关系表达式:RelationalExpression 实例的 ReferenceType
如果将 RelationalExpression 强制转换为 ReferenceType 会因为编译时错误而被拒绝,那么 instanceof
关系表达式同样会产生编译时错误.在这种情况下,instanceof
表达式的结果永远不会为真.
也就是说,因为这个强制转换表达式会产生一个编译时错误:
(数字) "foo"
这个表达式也必须:
("foo" instanceof Number)
<小时>
你的情况有点微妙,但原理是一样的:
String
是最终类String
没有实现Cloneable
- 因此你不能做
(Cloneable) aString
- 因此你也不能做
aString 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?
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
:
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. In such a situation, the result of theinstanceof
expression could never be true.
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 classString
does not implementCloneable
- Therefore you can't do
(Cloneable) aString
- Therefore also you can't do
aString instanceof Cloneable
这篇关于instanceof - 不兼容的条件操作数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!