Is null check needed before calling instanceof?

null instanceof SomeClass返回false或抛出一个NullPointerException


No, a null check is not needed before using instanceof.

The expression x instanceof SomeClass is false if x is null .

From the Java Language Specification, section 15.2.2, "Type comparison operator instanceof":

"At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException . Otherwise the result is false ."

So if the operand is null, the result is false.


使用空引用作为instanceof的第一个操作数返回false


Very good question indeed. I just tried for myself.

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));
    }
}

Prints

true
true
false
false

JLS / 15.20.2. Type Comparison Operator instanceof

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException . Otherwise the result is false .

API / Class#isInstance(Object)

If this Class object represents an interface, this method returns true if the class or any superclass of the specified Object argument implements this interface; it returns false otherwise. If this Class object represents a primitive type, this method returns false .

链接地址: http://www.djcxy.com/p/2140.html

上一篇: 如何避免JSP文件中的Java代码?

下一篇: 在调用instanceof之前是否需要空值检查?