Is null check needed before calling instanceof?
不,在使用InstanceOf之前不需要进行空检查。
如果
从Java语言规范,第1520.2节,"类型比较运算符实例":
"At run time, the result of the
instanceof operator istrue if the
value of the RelationalExpression is
notnull and the reference could be
cast to the ReferenceType
without raising aClassCastException .
Otherwise the result isfalse ."
因此,如果操作数为空,则结果为假。
使用空引用作为
这个问题真的很好。我只是为自己而努力。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
印刷品
1 2 3 4 | true true false false |
JLS/1520.2.类型比较运算符实例
At run time, the result of the
instanceof operator istrue if the value of the RelationalExpression is notnull and the reference could be cast to the ReferenceType without raising aClassCastException . Otherwise the result isfalse .
API/类IsInstance(对象)
If this
Class object represents an interface, this method returnstrue if the class or any superclass of the specifiedObject argument implements this interface; it returnsfalse otherwise. If thisClass object represents a primitive type, this method returnsfalse .
不,不是。如果第一个操作数是
就像小道消息:
即使是
(如果排版
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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). } } |
因此,
附言:如果你在招聘,请不要把这当作一个面试问题。D
不,Java文本EDCOX1(4)不是任何类的实例。因此,它不能是任何类的实例。
在运行时,如果关系表达式的值不是
如果操作数是
考虑下面的例子,
1 2 3 4 5 6 7 8 | 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"); } } |
1 2 3 4 5 6 7 8 9 | 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"); } } |