我的问题是,从new Test()
开始不是 String
的子类或者它是字符串本身那么为什么 instanceof
编译失败?它不应该返回false吗?
public class Test{
public static void main(String[] args) {
//Compiles fails
System.out.println(new Test() instanceof String);
//compiles fine but run time class cast exception.
Test = (Test) new Object();;
}
}
现在我已经编辑了我的帖子,所以这就是我真正想知道为什么会出现这种差异。为什么编译在转换时没有失败,尽管它应该失败
最佳答案
instanceof
如果在编译时保证始终返回 false,则无法应用。
规则是,如果将第一个操作数转换为第二个操作数的类型总是会抛出 ClassCastException
,则编译器不允许对这些操作数应用 instanceof
运算符操作数。
Test
类的实例永远不能是java.lang.String
的实例。
15.20.2. Type Comparison Operator instanceof
If a cast (§15.16) 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.
关于java - 为什么在 instanceof 运算符上编译时会出现错误,但在强制转换时却可以正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42622950/