Java中的instanceof - 为什么不编译? [英] instanceof in Java - why doesn't this compile?

查看:117
本文介绍了Java中的instanceof - 为什么不编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class A {

    public static void main(String...args) {
        Integer var = 10; 

        if(var instanceof Character)  // Line1
            System.out.println("var is a Character");
    }
}

我知道第1行将无法编译,因为编译器发现 var 不是字符

I know Line 1 will not compile because the compiler has found that var is not a Character.

我无法理解为什么编译器会抛出错误而不是返回 false true

What I fail to understand is why the compiler throws an error instead of returning false or true.

如果编译器返回 false true (即像处理基于if的常规验证一样处理 instanceof 操作,然后它会更有用..它不会吗?

If the compiler returns false or true (i.e treating the instanceof operation like a regular if-based validation), then it be much more useful.. would it not?

或者我错过了一些明显的东西?

Or am I missing something obvious?

推荐答案

根据JLS§15.20.2


如果将 RelationalExpression 转换为 ReferenceType 作为编译时错误被拒绝,那么 instanceof 关系ex压力同样产生编译时错误。在这种情况下, 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.

RelationalExpression instanceof 的第一个操作数, ReferenceType 是第二个。

RelationalExpression is the first operand of instanceof and ReferenceType is the second.

这篇关于Java中的instanceof - 为什么不编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆