instanceof in Java - why doesn't this compile? [duplicate]

浪尽此生 提交于 2019-12-05 10:38:01

问题


class A {

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

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

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

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

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?


回答1:


It's a compilation error in accordance with 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. In such a situation, the result of the instanceof expression could never be true.

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




回答2:


In addition to the arshajii's answer if you want to avoid compile-time error and want run-time true/false result for checking whether var is instance of Character then use code like this:

if(var.getClass().isAssignableFrom(Character.class))
    System.out.println("var is a Character");
else
    System.out.println("var is NOT a Character");

As you would expect it will print:

var is NOT a Character


来源:https://stackoverflow.com/questions/18548436/instanceof-in-java-why-doesnt-this-compile

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!