在 Java 中检查 null 值的最佳方法是什么?

在调用对象的函数之前,我需要检查对象是否为 null,以避免抛出 NullPointerException

最好的方法是什么? 我已经考虑过这些方法。
哪一个是 Java 的最佳编程实践?

// 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...
}
335043 次浏览

The last and the best one. i.e LOGICAL AND

  if (foo != null && foo.bar()) {
etc...
}

Because in logical &&

it is not necessary to know what the right hand side is, the result must be false

Prefer to read :Java logical operator short-circuiting

Method 4 is best.

if(foo != null && foo.bar()) {
someStuff();
}

will use short-circuit evaluation, meaning it ends if the first condition of a logical AND is false.

  • Do not catch NullPointerException. That is a bad practice. It is better to ensure that the value is not null.
  • Method #4 will work for you. It will not evaluate the second condition, because Java has short-circuiting (i.e., subsequent conditions will not be evaluated if they do not change the end-result of the boolean expression). In this case, if the first expression of a logical AND evaluates to false, subsequent expressions do not need to be evaluated.

I would say method 4 is the most general idiom from the code that I've looked at. But this always feels a bit smelly to me. It assumes foo == null is the same as foo.bar() == false.

That doesn't always feel right to me.

Method 4 is my preferred method. The short circuit of the && operator makes the code the most readable. Method 3, Catching NullPointerException, is frowned upon most of the time when a simple null check would suffice.

Method 4 is far and away the best as it clearly indicates what will happen and uses the minimum of code.

Method 3 is just wrong on every level. You know the item may be null so it's not an exceptional situation it's something you should check for.

Method 2 is just making it more complicated than it needs to be.

Method 1 is just method 4 with an extra line of code.

if you do not have an access to the commons apache library, the following probably will work ok

if(null != foo && foo.bar()) {
//do something
}

Your last proposal is the best.

if (foo != null && foo.bar()) {
etc...
}

Because:

  1. It is easier to read.
  2. It is safe : foo.bar() will never be executed if foo == null.
  3. It prevents from bad practice such as catching NullPointerExceptions (most of the time due to a bug in your code)
  4. It should execute as fast or even faster than other methods (even though I think it should be almost impossible to notice it).

If you control the API being called, consider using Guava's Optional class

More info here. Change your method to return an Optional<Boolean> instead of a Boolean.

This informs the calling code that it must account for the possibility of null, by calling one of the handy methods in Optional

In Java 7, you can use Objects.requireNonNull(). Add an import of Objects class from java.util.

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");
}
//...
}

As others have said #4 is the best method when not using a library method. However you should always put null on the left side of the comparison to ensure you don't accidentally assign null to foo in case of typo. In that case the compiler will catch the mistake.

// 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){

We can use Object.requireNonNull static method of Object class. Implementation is below

public void someMethod(SomeClass obj) {
Objects.requireNonNull(obj, "Validation error, obj cannot be null");
}

Simple one line Code to check for null :

namVar == null ? codTdoForNul() : codTdoForFul();

You also can use StringUtils.isNoneEmpty("") for check is null or empty.

Correction: This is only true for C/C++ not for Java, sorry.

If at all you going to check with double equal "==" then check null with object ref like

if(null == obj)

instead of

if(obj == null)

because if you mistype single equal if(obj = null) it will return true (assigning object returns success (which is 'true' in value).

Since java 8 you can use Objects.nonNull(Object obj)

if(nonNull(foo)){
//
}
public <T, U> U defaultGet(T supplier, Function<T, U> mapper, U defaultValue) {
return Optional.ofNullable(supplier).map(mapper).orElse(defaultValue);


}

You can create this function if you prefer function programming

Update

I created a java library(Maven Dependency) for the java developers to remove this NullPointerException Hell from their code. Check out my repository.

NullUtil Repository

Generic Method to handle Null Values in Java

<script src="https://gist.github.com/rcvaram/f1a1b89193baa1de39121386d5f865bc.js"></script>

  1. If that object is not null we are going to do the following things.

    a. We can mutate the object (I)

    b. We can return something(O) as output instead of mutating the object (I)

    c. we can do both

In this case, We need to pass a function which needs to take the input param(I) which is our object If we take it like that, then we can mutate that object if we want. and also that function may be something (O).

  1. If an object is null then we are going to do the following things

    a. We may throw an exception in a customized way

    b. We may return something.

In this case, the object is null so we need to supply the value or we may need to throw an exception.

I take two examples.

  1. If I want to execute trim in a String then that string should not be null. In that case, we have to additionally check the null value otherwise we will get NullPointerException
public String trimValue(String s){
return s == null ? null : s.trim();
}
  1. Another function which I want to set a new value to object if that object is not null otherwise I want to throw a runtime exception.
public void setTeacherAge(Teacher teacher, int age){
if (teacher != null){
teacher.setAge(age);
} else{
throw new RuntimeException("teacher is null")
}
}


With my Explanation, I have created a generic method that takes the value(value may be null), a function that will execute if the object is not null and another supplier function that will execute if the object is null.

GenericFunction

  public <I, O> O setNullCheckExecutor(I value, Function<I, O> nonNullExecutor, Supplier<O> nullExecutor) {
return value != null ? nonNullExecutor.apply(value) : nullExecutor.get();
}

So after having this generic function, we can do as follow for the example methods 1.

//To Trim a value
String trimmedValue = setNullCheckExecutor(value, String::trim, () -> null);


Here, the nonNullExecutor Function is trim the value (Method Reference is used). nullExecutorFunction is will return null since It is an identity function.

2.

// mutate the object if not null otherwise throw a custom message runtime exception instead of NullPointerException
setNullCheckExecutor(teacher, teacher -> {
teacher.setAge(19);
return null;
}, () -> {
throw new RuntimeException("Teacher is null");
});

Allot of times I look for null when processing a function -

public static void doSomething(Object nullOrNestedObject) {
if (nullOrNestedObject == null || nullOrNestedObject.getNestedObject()) {
log.warn("Invalid argument !" );
return;
// Or throw an exception
// throw new IllegalArgumentException("Invalid argument!");


}
nullOrNestedObject.getNestedObject().process()
... // Do other function stuff
}

That way if it is null it just stops execution early, and you don't have to nest all of your logic in an if.