Best way to check for null values in Java?

后端 未结 16 1264
傲寒
傲寒 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 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");
        }
        //...
    }
    

提交回复
热议问题