함수를 호출하기 전에 객체의 데릭쉐퍼드와 여부를 확인할 것을 막기 위해 '' 누얼포인터렉세페시옹 널임 객체에는 던진다.
What is the best way to go 이건? # 39 이 방법, ve i& 여겨진다. < br/>; 자바 프로그래밍 어느쪽이야 가장 좋은 방법은?
// Method 1
if (foo != null) {
if (foo.bar()) {
etc...
}
}
// Method 2
if (foo != null ? foo.bar() : false) {
etc...
}
// Method 3
try {
if (foo.bar()) {
etc...
}
} catch (NullPointerException e) {
}
// Method 4 -- Would this work, or would it still call foo.bar()?
if (foo != null && foo.bar()) {
etc...
}
if(foo != null && foo.bar()) {
someStuff();
}
[단락 평가] [1], 즉 첫 번째 motor1.1end 사용할 경우 '와' 는 논리 상태를 거짓값.
[1]: http://en.wikipedia.org/wiki/Short-circuit_evaluation # Avoiding_the_execution_of_second_expression.27s_side_effects
가장 마지막 한. 이리에 논리적,
if (foo != null && foo.bar()) {
etc...
}
논리 ',' & & 있기 때문이다.
>. 필요한 것은 무엇인지, 그 결과 오른쪽 면은 거짓값 있어야 합니다.
선호하는 검토완료: https://stackoverflow.com/questions/8759868/java-logcial-operators-short-circuiting
자바 가상 머신 (jvm) 에 8 가장 좋은 방법은 확인할지 nulll 입니다.
Objects.isNull(obj) //returns true if the object is null
Objects.nonNull(obj) //returns true if object is not-null
if(Objects.nonNull(foo) && foo.something()) // Uses short-circuit as well. No Null-pointer Exceptions are thrown.
이와 별도로. # 39 의 옵션임 클래스용 Guava& 함께 사용할 수도 있습니다.
항상 같은 오류를 줄일 수 있는 'true' 되돌려줍니다 유형학적 ' (obj = null)' 에서 설명한 것처럼 이전 분입니다.
public class FooClass {
//...
public void acceptFoo(Foo obj) {
//If obj is null, NPE is thrown
Objects.requireNonNull(obj).bar(); //or better requireNonNull(obj, "obj is null");
}
//...
}
Api 를 호출할 경우, 사용을 고려해보십시오 컨트롤입니다 Guava& # 39 의 옵션임 클래스
자세한 정보 here. 대신, ',' 한 'Optional< 메서드로부터 변경하십시오 반환되기를 Boolean> 부울입니다'.
이 ingdbextr 호출하는 코드를 통해 가능성을 고려해야 한다는 '옵션' the handy 의 방법 중 하나를 호출하십시오 nulll
// You meant to do this
if(foo != null){
// But you made a typo like this which will always evaluate to true
if(foo = null)
// Do the comparison in this way
if(null != foo)
// So if you make the mistake in this way the compiler will catch it
if(null = foo){
// obviously the typo is less obvious when doing an equality comparison but it's a good habit either way
if(foo == null){
if(foo = null){
아파치 커먼즈 라이브러리에 액세스할 수 없는 경우, 다음과 같은 결과를 확인 할 것이다.
if(null != foo && foo.bar()) {
//do something
}
네 마지막 제안은 최고라니까요
if (foo != null && foo.bar()) {
etc...
}
이유: