How to avoid NPE

if(null!=person){
    ...
    if(null!=address){
        ...
        if(null!=phone){
            ...
        }
    }

}

NO

Elegant avoidance of null pointer exceptions

I Tool class

coordinate

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>

For string

String name="";
boolean blank = StringUtils.isBlank(name);
System.out.println(blank);

coordinate

<dependency>
    <groupId>commons-collections</groupId>
    <artifactId>commons-collections</artifactId>
    <version>3.2.2</version>
</dependency>

For collection

boolean empty = CollectionUtils.isEmpty(new ArrayList());
System.out.println(empty);

The above two tool classes are also reused in real projects. They are safer than writing a pile of if to judge

As we know, the back end usually queries multiple pieces of data from the DB, encapsulates a collection and gives it to the front end for rendering. Once the collection is empty, an error NPE will be reported. The previous tool classes can help us make a good judgment. There are probably two ways to do it

II Optional

Located in Java Optional under util package is a jdk8 newly added final tool class. We can use it to flexibly judge and handle in a functional style

It has the following factory methods to create optional objects

public static <T> Optional<T> of(T value) {
    return new Optional<>(value);
}
public static<T> Optional<T> empty() {
    @SuppressWarnings("unchecked")
    Optional<T> t = (Optional<T>) EMPTY;
    return t;
}
public static <T> Optional<T> ofNullable(T value) {
    return value == null ? empty() : of(value);
}

The following methods introduce a functional programming style

System.out.println(optional.orElse("hello"));
System.out.println(optional.orElseGet(()->"haha"));

How to replace with functional programming style

if(null!=list){
        return list;
    }else{
        return new ArrayList():
    }
//模拟后端的查询出来的结果
List<student> list = Arrays.asList(new student(1,"123"),new student(2,"123"));
OptionalText optionalText = new OptionalText();
optionalText.setStuList(list);

//创容器
Optional<OptionalText> optional1 = optional.ofNullable(optionalText);
//容器里面对象的list如果有值则返回,如果没有,则返回空list
List<student> students = optional1.map(item -> item.getStuList()).orElse(new ArrayList<student>());
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>