Java 在调用 instanceof 之前是否需要进行空检查?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2950319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:50:54  来源:igfitidea点击:

Is null check needed before calling instanceof?

javanullpointerexceptionnull

提问by Johan Lübcke

Will null instanceof SomeClassreturn falseor throw a NullPointerException?

null instanceof SomeClass返回false还是抛出一个NullPointerException

采纳答案by Andy Thomas

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

不,在使用 instanceof 之前不需要空检查。

The expression x instanceof SomeClassis falseif xis null.

表达式x instanceof SomeClassfalseif xis null

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

来自 Java Language Specification,第 15.20.2 节,“类型比较运算符 instanceof”

"At run time, the result of the instanceofoperator is trueif the value of the RelationalExpressionis not nulland the reference could be cast to the ReferenceTypewithout raising a ClassCastException. Otherwise the result is false."

“在运行时,instanceof运算符的结果 是,true如果RelationalExpression的值不是,null并且可以将引用强制转换为ReferenceType而不会引发ClassCastException。否则结果是false。”

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

因此,如果操作数为空,则结果为假。

回答by Bozho

Using a null reference as the first operand to instanceofreturns false.

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

回答by RoflcoptrException

No, it's not. instanceofwould return falseif its first operand is null.

不,这不对。如果它的第一个操作数是 ,则instanceof返回。falsenull

回答by Jin Kwon

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

JLS / 15.20.2。类型比较运算符 instanceof

At run time, the result of the instanceofoperator is trueif the value of the RelationalExpressionis not nulland the reference could be cast to the ReferenceTypewithout raising a ClassCastException. Otherwise the result is false.

在运行时,instanceof运算符的结果是RelationalExpressiontrue的值是否不是,并且可以将引用强制转换为ReferenceType而不引发. 否则结果是。nullClassCastExceptionfalse

API / Class#isInstance(Object)

API / 类#isInstance(对象)

If this Classobject represents an interface, this method returns trueif the class or any superclass of the specified Objectargument implements this interface; it returns falseotherwise. If this Classobject represents a primitive type, this method returns false.

如果此Class对象表示一个接口,true则如果指定Object参数的类或任何超类实现此接口,则此方法返回;否则返回false。如果此Class对象表示原始类型,则此方法返回false

回答by Nikhil Kumar

The instanceofoperator does not need explicit nullchecks, as it does not throw a NullPointerExceptionif the operand is null.

instanceof运营商并不需要显式的null检查,因为它不会抛出NullPointerException,如果操作数null

At run time, the result of the instanceofoperator is true if the value of the relational expression is not nulland the reference could be cast to the reference type without raising a class cast exception.

在运行时,instanceof如果关系表达式的值不是,null并且可以将引用强制转换为引用类型而不引发类强制转换异常,则运算符的结果为真。

If the operand is null, the instanceofoperator returns falseand hence, explicit null checks are not required.

如果操作数是null,则instanceof运算符返回false,因此不需要显式空检查。

Consider the below example,

考虑下面的例子,

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

The correct usage of instanceofis as shown below,

的正确用法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");
??????? ?}  
}

回答by Developer Marius ?il?nas

No. Java literal nullis not an instance of any class. Therefore it can not be an instanceofany class. instanceofwill return either falseor truetherefore the <referenceVariable> instanceof <SomeClass>returns falsewhen referenceVariablevalue is null.

没有。Java 文字null不是任何类的实例。因此它不能是任何类的实例。当value 为 null时,instanceof将返回falsetrue因此<referenceVariable> instanceof <SomeClass>返回。falsereferenceVariable

回答by Attila Tanyi

Just as a tidbit:

就像一个花絮

Even (((A)null)instanceof A)will return false.

甚至会回来。(((A)null)instanceof A)false



(If typecasting nullseems surprising, sometimes you have to do it, for example in situations like this:

(如果类型转换null看起来令人惊讶,有时您必须这样做,例如在这样的情况下:

public class Test
{
  public static void test(A a)
  {
    System.out.println("a instanceof A: " + (a instanceof A));
  }

  public static void test(B b) {
    // Overloaded version. Would cause reference ambiguity (compile error)
    // if Test.test(null) was called without casting.
    // So you need to call Test.test((A)null) or Test.test((B)null).
  }
}

So Test.test((A)null)will print a instanceof A: false.)

所以Test.test((A)null)会打印a instanceof A: false。)



P.S.: If you are hiring, please don't use this as a job interview question. :D

PS:如果您正在招聘,请不要将此作为求职面试问题。:D