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
. 당신은 테스트에서 볼 수 있듯이 1 과 2 , null
그리고 modifiedItems.get("item1")
동등하고 있습니다 null
.
동작은 Java 7 및 8에서 동일합니다.
어떤 과부하가 호출되는지주의 깊게 살펴 봐야합니다.
Boolean.valueOf(null)
호출 중Boolean.valueOf(String)
입니다.NPE
null 매개 변수가 제공 되어도 짝수를 던지지 않습니다 .Boolean.valueOf(modifiedItems.get("item1"))
의 값이 형식 이므로 unboxing 변환이 필요Boolean.valueOf(boolean)
하기 때문에 호출modifiedItems
중입니다Boolean
.modifiedItems.get("item1")
is 이므로 NPE를 던지는null
값이 아닌 해당 값의 언 박싱입니다Boolean.valueOf(...)
.
어떤 과부하가 호출되는지를 결정하는 규칙은 꽤 털이 있지만 대략 다음과 같습니다.
첫 번째 단계에서, boxing / unboxing (가변 arity 방법)을 허용하지 않고 method match가 검색됩니다.
- 왜냐하면
null
A에 대한 허용 값은String
아니지만boolean
,Boolean.valueOf(null)
에 매칭Boolean.valueOf(String)
이 패스; Boolean
Boolean.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())
- A는
(다양한 arity 방법을 허용하는 세 번째 패스가 있지만 처음 두 패스가 이러한 경우와 일치하므로 여기에는 관련이 없습니다)
이후 modifiedItems.get
리턴한다 Boolean
(이다 하지 스트 String
)이며, 사용되는 서명 Boolean.valueOf(boolean)
가 Boolean
원시적으로 outboxed됩니다 boolean
. null
반환 되면 발신 함이로 실패합니다 NullPointerException
.
메소드 서명
이 방법 Boolean.valueOf(...)
에는 두 가지 서명이 있습니다.
public static Boolean valueOf(boolean b)
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.
- byte - Byte
- char - Character
- float - Float
- int - Integer
- long - Long
- short - Short
- 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
'program tip' 카테고리의 다른 글
부트 스트랩 서버에 등록 할 수 없습니다 (0) | 2020.07.27 |
---|---|
서버가 FB 페이지 정보를 가져 오기위한 오래 지속되는 FB 액세스 토큰 (0) | 2020.07.27 |
빠르고 반응이 빠른 대화식 차트 / 그래프 : SVG, Canvas, 기타? (0) | 2020.07.27 |
NSObject +로드 및 + 초기화-어떻게합니까? (0) | 2020.07.27 |
TensorFlow에서 Variable과 get_variable의 차이점 (0) | 2020.07.27 |