Best way to check for null values in Java?

后端 未结 16 1090
傲寒
傲寒 2020-12-04 16:30

Before calling a function of an object, I need to check if the object is null, to avoid throwing a NullPointerException.

What is the best way to go abou

相关标签:
16条回答
  • 2020-12-04 16:59

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

    0 讨论(0)
  • 2020-12-04 17:00

    In Java 8, the best way to check for null is:

    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.
    

    Apart from this... You can also go with Guava's Optional Class

    0 讨论(0)
  • 2020-12-04 17:04

    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.

    0 讨论(0)
  • 2020-12-04 17:09

    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");
        }
        //...
    }
    
    0 讨论(0)
  • 2020-12-04 17:09

    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
    }
    
    0 讨论(0)
  • 2020-12-04 17:11

    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.

    0 讨论(0)
提交回复
热议问题