etc./StackOverFlow

instanceof를 호출하기 전에 null 검사가 필요합니까?

청렴결백한 만능 재주꾼 2022. 3. 4. 07:55
반응형

질문자 :Johan Lübcke


null instanceof SomeClass false 반환하거나 NullPointerException throw합니까?



아니요, instanceof를 사용하기 전에 null 검사가 필요하지 않습니다.

x instanceof SomeClass 표현식은 xnull false 입니다.

Java 언어 사양, 섹션 15.20.2, "유형 비교 연산자 instanceof"에서 :

"런타임에 결과 instanceof 연산자는 true RelationalExpression의 값이없는 경우 null 과 기준은 제기하지 않고있는 ReferenceType에 캐스트 할 수 ClassCastException . 그렇지 않으면 결과는 false ."

따라서 피연산자가 null이면 결과는 false입니다.


Andy Thomas

instanceof 대한 첫 번째 피연산자로 null 참조를 사용하면 false 반환됩니다.


Bozho

정말 좋은 질문입니다. 나는 단지 나 자신을 위해 노력했다.

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

인쇄물

 true true false false

JLS / 15.20.2. 유형 비교 연산자 instanceof

런타임에 RelationalExpression 의 값이 null 이 아니고 ClassCastException 을 발생시키지 않고 ReferenceType 으로 캐스트될 수 있는 instanceof 연산자의 결과 true 입니다. 그렇지 않으면 결과는 false 입니다.

API / 클래스#isInstance(객체)

Class 객체가 인터페이스를 나타내는 Object 인수의 클래스 또는 수퍼클래스가 이 인터페이스를 구현 true false 반환합니다. Class 객체가 기본 유형을 나타내는 경우 이 false 반환합니다.


Jin Kwon

아니, 그렇지 않다. instanceof 는 첫 번째 피연산자가 null false 반환합니다.


RoflcoptrException

그냥 재미있는 이야기로 :

심지어 ( ((A)null) instanceof A) false 를 반환합니다.


(만약 null typecasting이 놀랍다면, 예를 들어 다음과 같은 상황에서 때때로 그것을 해야 합니다:

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

따라서 Test.test((A)null)a instanceof A: false 인쇄합니다.)


추신: 채용 중이라면 이것을 면접 질문으로 사용하지 마십시오. :NS


Attila Tanyi

instanceof 연산자는 피연산자가 null NullPointerException throw하지 않으므로 null 검사가 필요하지 않습니다.

런타임에 instanceof 연산자의 결과는 관계식의 값이 null 이 아니고 클래스 캐스트 예외를 발생시키지 않고 참조를 참조 유형으로 캐스트할 수 있는 경우 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");        } }

Nikhil Kumar

  • instanceof 전에 null 검사가 필요하지 않습니다.
  • true로 검증된 instanceof 이후 에는 널 검사가 필요하지 않습니다.

다음은 널로부터 안전합니다.

 if(couldbenull instanceof Comparable comp){ return comp.compareTo(somethingElse); }
 //java < 14 if(couldbenull instanceof Comparable){ return ((Comparable)couldbenull).compareTo(somethingElse); }

Marinos An

출처 : http:www.stackoverflow.com/questions/2950319/is-null-check-needed-before-calling-instanceof

반응형