program tip

Boolean.valueOf ()는 때때로 NullPointerException을 생성합니다.

radiobox 2020. 7. 27. 07:49
반응형

Boolean.valueOf ()는 때때로 NullPointerException을 생성합니다.


이 코드가 있습니다 :

package tests;

import java.util.Hashtable;

public class Tests {

    public static void main(String[] args) {

        Hashtable<String, Boolean> modifiedItems = new Hashtable<String, Boolean>();

        System.out.println("TEST 1");
        System.out.println(modifiedItems.get("item1")); // Prints null
        System.out.println("TEST 2");
        System.out.println(modifiedItems.get("item1") == null); // Prints true
        System.out.println("TEST 3");
        System.out.println(Boolean.valueOf(null)); // Prints false
        System.out.println("TEST 4");
        System.out.println(Boolean.valueOf(modifiedItems.get("item1"))); // Produces NullPointerException
        System.out.println("FINISHED!"); // Never executed
    }
}

내 문제는 내가 왜 이해하지 못하는 것입니다 테스트 (3)가 잘 작동 (가 인쇄 false및 생산하지 않는 NullPointerException사이에) 시험 4 발생합니다 NullPointerException. 당신은 테스트에서 볼 수 있듯이 12 , null그리고 modifiedItems.get("item1")동등하고 있습니다 null.

동작은 Java 7 및 8에서 동일합니다.


어떤 과부하가 호출되는지주의 깊게 살펴 봐야합니다.

  • Boolean.valueOf(null)호출 중 Boolean.valueOf(String)입니다. NPEnull 매개 변수가 제공 되어도 짝수를 던지지 않습니다 .
  • Boolean.valueOf(modifiedItems.get("item1"))의 값이 형식 이므로 unboxing 변환이 필요 Boolean.valueOf(boolean)하기 때문에 호출 modifiedItems중입니다 Boolean. modifiedItems.get("item1")is 이므로 NPE를 던지는 null값이 아닌 해당 값의 언 박싱입니다 Boolean.valueOf(...).

어떤 과부하가 호출되는지를 결정하는 규칙은 꽤 털이 있지만 대략 다음과 같습니다.

  • 첫 번째 단계에서, boxing / unboxing (가변 arity 방법)을 허용하지 않고 method match가 검색됩니다.

    • 왜냐하면 nullA에 대한 허용 값은 String아니지만 boolean, Boolean.valueOf(null)에 매칭 Boolean.valueOf(String)이 패스;
    • BooleanBoolean.valueOf(String)또는에 허용되지 않으므로에 대한 Boolean.valueOf(boolean)이 패스에서 일치하는 방법이 없습니다 Boolean.valueOf(modifiedItems.get("item1")).
  • 두 번째 단계에서는 복싱 / 언 박싱을 허용하는 메소드 일치가 검색됩니다 (그러나 여전히 가변적 인 arity 메소드는 아님).

    • A는 Boolean로 박싱 될 수 boolean있으므로, Boolean.valueOf(boolean)에 대한 매칭 Boolean.valueOf(modifiedItems.get("item1"))이 패스; 그러나 unboxing 변환은 컴파일러에 의해 삽입되어 호출되어야합니다.Boolean.valueOf(modifiedItems.get("item1").booleanValue())
  • (다양한 arity 방법을 허용하는 세 번째 패스가 있지만 처음 두 패스가 이러한 경우와 일치하므로 여기에는 관련이 없습니다)


이후 modifiedItems.get리턴한다 Boolean(이다 하지 스트 String)이며, 사용되는 서명 Boolean.valueOf(boolean)Boolean원시적으로 outboxed됩니다 boolean. null반환 되면 발신 함이로 실패합니다 NullPointerException.


메소드 서명

이 방법 Boolean.valueOf(...)에는 두 가지 서명이 있습니다.

  1. public static Boolean valueOf(boolean b)
  2. public static Boolean valueOf(String s)

Your modifiedItems value is Boolean. You cannot cast Boolean to String so consequently the first signature will be chosen

Boolean unboxing

In your statement

Boolean.valueOf(modifiedItems.get("item1"))

which can be read as

Boolean.valueOf(modifiedItems.get("item1").booleanValue())   

However, modifiedItems.get("item1") returns null so you'll basically have

null.booleanValue()

which obviously leads to a NullPointerException


As Andy already very well described the reason of NullPointerException:

which is due to Boolean un-boxing:

Boolean.valueOf(modifiedItems.get("item1"))

get converted into:

Boolean.valueOf(modifiedItems.get("item1").booleanValue())

at runtime and then it throw NullPointerException if modifiedItems.get("item1") is null.

Now I would like to add one more point here that un-boxing of the following classes to their respective primitives can also produce NullPointerException exception if their corresponding returned objects are null.

  1. byte - Byte
  2. char - Character
  3. float - Float
  4. int - Integer
  5. long - Long
  6. short - Short
  7. double - Double

Here is the code:

    Hashtable<String, Boolean> modifiedItems1 = new Hashtable<String, Boolean>();
    System.out.println(Boolean.valueOf(modifiedItems1.get("item1")));//Exception in thread "main" java.lang.NullPointerException

    Hashtable<String, Byte> modifiedItems2 = new Hashtable<String, Byte>();
    System.out.println(Byte.valueOf(modifiedItems2.get("item1")));//Exception in thread "main" java.lang.NullPointerException

    Hashtable<String, Character> modifiedItems3 = new Hashtable<String, Character>();
    System.out.println(Character.valueOf(modifiedItems3.get("item1")));//Exception in thread "main" java.lang.NullPointerException

    Hashtable<String, Float> modifiedItems4 = new Hashtable<String, Float>();
    System.out.println(Float.valueOf(modifiedItems4.get("item1")));//Exception in thread "main" java.lang.NullPointerException

    Hashtable<String, Integer> modifiedItems5 = new Hashtable<String, Integer>();
    System.out.println(Integer.valueOf(modifiedItems5.get("item1")));//Exception in thread "main" java.lang.NullPointerException

    Hashtable<String, Long> modifiedItems6 = new Hashtable<String, Long>();
    System.out.println(Long.valueOf(modifiedItems6.get("item1")));//Exception in thread "main" java.lang.NullPointerException

    Hashtable<String, Short> modifiedItems7 = new Hashtable<String, Short>();
    System.out.println(Short.valueOf(modifiedItems7.get("item1")));//Exception in thread "main" java.lang.NullPointerException

    Hashtable<String, Double> modifiedItems8 = new Hashtable<String, Double>();
    System.out.println(Double.valueOf(modifiedItems8.get("item1")));//Exception in thread "main" java.lang.NullPointerException

A way to understand it is when Boolean.valueOf(null) is invoked, java is precisely being told to evaluate null.

However, when Boolean.valueOf(modifiedItems.get("item1")) is invoked, java is told to obtain a value from the HashTable of object type Boolean, but it doesn't find the type Boolean it finds a dead end instead (null) even though it expected Boolean. The NullPointerException exception is thrown because the creators of this part of java decided this situation is an instance of something in the program going wrong that needs the programmer's attention. (Something unintended happened.)

In this case it is more the difference between deliberately declaring that you intended the null to be there, and java finding a missing reference to an object (null) where an object was intended to be found.

See more information about NullPointerException in this answer: https://stackoverflow.com/a/25721181/4425643

참고URL : https://stackoverflow.com/questions/46601104/boolean-valueof-produces-nullpointerexception-sometimes

반응형