java - 为什么在 instanceof 运算符上编译时会出现错误,但在强制转换时却可以正常工作

标签 java instanceof

我的问题是,从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/

相关文章:

java - 使用 Jackson 将 JSON 反序列化为具有重载方法的对象

java - 如何使用 WebDriver 将字符串保存为变量,然后在另一个测试中使用 tis 变量

java - 如果我只能获取某个类的对象,但我的方法只能在子类上工作,如何避免使用instanceof

java - 类继承

java - 无法转换 org.apache.batik.bridge.UpdateManager

java - JOptionPane 没有带有自定义 LNF 的按钮文本

java - 在 Java 中,如何保持原始窗口的焦点,尽管单击 JFrame

java - 使用instanceof进行编译时检查

javascript - 性能:typeof vs instanceof

android - 有什么办法可以避免在 Android 中使用 instanceOf 吗?