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

坚强是说给别人听的谎言 提交于 2019-12-03 22:38:01

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.

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