[英]instanceof with custom/core classes
Why can I test my custom class against my custom interface using instanceof
and I am unable to do the same with java core classes? 为什么我可以使用
instanceof
针对我的自定义界面测试我的自定义类,我无法对java核心类做同样的事情?
interface A{}
class B{}
public class Tmp {
public static void main(String [] args) {
String s = "";
Integer i = 1;
B b = new B();
System.out.println(s instanceof A); //1
System.out.println(i instanceof A); //2
System.out.println(b instanceof A); //3
}
}
Lines 1 and 2 won't compile. 第1行和第2行不会编译。 Line 3 will compile (and print
false
). 第3行将编译(并打印为
false
)。 What's the difference? 有什么不同?
If the compiler can detect that the instanceof
operation could never be true it will generate a compiler error. 如果编译器可以检测到
instanceof
操作永远不会为true,则会生成编译器错误。 It determines this by following the same rules as that for casting. 它通过遵循与投射相同的规则来确定这一点。 The specific rule is described in Section 15.20.2 of the JLS:
具体规则在JLS的第15.20.2节中描述:
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将作为编译时错误被拒绝,则关系表达式的实例同样会产生编译时错误。 In such a situation, the result of the instanceof expression could never be true.
在这种情况下,instanceof表达式的结果永远不会成立。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.