null instanceof SomeClass
返回false
仍是抛出NullPointerException
? html
确实,这是一个很好的问题。 我只是为本身而努力。 java
public class IsInstanceOfTest { public static void main(final String[] args) { String s; s = ""; System.out.println((s instanceof String)); System.out.println(String.class.isInstance(s)); s = null; System.out.println((s instanceof String)); System.out.println(String.class.isInstance(s)); } }
版画 api
true true false false
JLS / 15.2.2。 类型比较运算符instanceof oracle
在运行时,若是RelationalExpression的值不为
null
而且能够将引用强制转换为ReferenceType而不引起ClassCastException
,则instanceof
运算符的结果为true
。 不然结果为false
。 ide
API / Class#isInstance(Object) spa
若是此
Class
对象表示一个接口,则若是指定Object
参数的类或任何超类实现此接口,则此方法返回true
不然,此方法返回true
。 不然返回false
。 若是此Class
对象表示原始类型,则此方法返回false
。 code
instanceof
运算符不须要显式的null
检查,由于若是操做数为null
,则它不会引起NullPointerException
。 htm
在运行时,若是关系表达式的值不为null
,而且引用能够强制转换为引用类型而不会引起类强制转换异常,则instanceof
运算符的结果为true。 对象
若是操做数为null
,则instanceof
运算符将返回false
,所以不须要显式的null检查。 接口
考虑下面的示例,
public static void main(String[] args) { if(lista != null && lista instanceof ArrayList) { //Violation System.out.println("In if block"); } else { System.out.println("In else block"); } }
正确使用instanceof
以下所示,
public static void main(String[] args) { if(lista instanceof ArrayList){ //Correct way System.out.println("In if block"); } else { System.out.println("In else block"); } }
使用null引用做为instanceof
的第一个操做数将返回false
。
不,这不对。 若是instanceof
的第一个操做数为null
则将返回false
。
不,使用instanceof以前不须要进行空检查。
若是x
为null
则表达式x instanceof SomeClass
为false
。
根据Java语言规范的第15.20.2节“类型比较运算符instanceof” :
“在运行时,结果
instanceof
运算符是true
,若是RelationalExpression的值不null
,并引用能够转换为引用类型不提升一个ClassCastException
。不然,结果是false
。”
所以,若是操做数为null,则结果为false。