原创

Java中利用Optional解决NullPointerException判断问题

构建Optional对象方法

empty()

返回指定类型的Optional空对象

private static final Optional<?> EMPTY = new Optional<>();

public static<T> Optional<T> empty() {
    @SuppressWarnings("unchecked")
    Optional<T> t = (Optional<T>) EMPTY;
    return t;
}

of(T value)

构建T类型的Optional对象,为null会抛出NullPointerException异常

public static <T> Optional<T> of(T value) {
    return new Optional<>(value);
}

ofNullable(T value)

构建T类型的Optional对象,允许为null

public static <T> Optional<T> ofNullable(T value) {
    return value == null ? empty() : of(value);
}

获取值的方法

get()

获得value的值,为null抛出NoSuchElementException异常

public T get() {
    if (value == null) {
        throw new NoSuchElementException("No value present");
    }
    return value;
}

orElse(T other)

获取value的值,为null返回指定的other的值,如果value为null也会调用other

public T orElse(T other) {
    return value != null ? value : other;
}

orElseGet(Supplier<? extends T> other)

获取value的值,为null返回Supplier的lambda类型的值,如果value不为null不会调用other

public T orElseGet(Supplier<? extends T> other) {
    return value != null ? value : other.get();
}

orElseThrow(Supplier<? extends X> exceptionSupplier)

获取value的值,为null抛出Supplier的lambda类型的异常。

public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
    if (value != null) {
        return value;
    } else {
        throw exceptionSupplier.get();
    }
}

eg

public void test() {
    User user = null;
    user = Optional.ofNullable(user).orElse(createUser());
    user = Optional.ofNullable(user).orElseGet(() -> createUser());
    Optional.ofNullable(user).orElseThrow(()->new Exception("用户不存在"));
}
public User createUser(){
    User user = new User();
    user.setName("zhangsan");
    return user;
}

判断value是否为null

isPresent()

返回当前值是否为null。

public boolean isPresent() {
    return value != null;
}

ifPresent(Consumer<? super T> consumer)

如果不为null,调用Consumer的lambda类型的表达式。

public void ifPresent(Consumer<? super T> consumer) {
    if (value != null)
        consumer.accept(value);
}

转换过滤值的操作

map(Function<? super T, ? extends U> mapper)

获取value中指定的值,接收一个Function的lambda类型的值。

public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
    Objects.requireNonNull(mapper);
    if (!isPresent())
        return empty();
    else {
        return Optional.ofNullable(mapper.apply(value));
    }
}

eg:

public class User {
    private String name;
    public String getName() {
        return name;
    }
}

String name = Optional.ofNullable(user).map(u-> u.getName()).get();

flatMap(Function<? super T, Optional<U>> mapper)

获取value中指定的值该值为Optional包装过的值,接收一个Function的lambda类型的值。

public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
    Objects.requireNonNull(mapper);
    if (!isPresent())
        return empty();
    else {
        return Objects.requireNonNull(mapper.apply(value));
    }
}

eg:

public class User {
    private String name;
    public Optional<String> getName() {
        return Optional.ofNullable(name);
    }
}

String name = Optional.ofNullable(user).flatMap(u-> u.getName()).get();

filter(Predicate<? super T> predicate)

为false返回EMPTY,接收一个Predicate的lambda类型的值。

public Optional<T> filter(Predicate<? super T> predicate) {
    Objects.requireNonNull(predicate);
    if (!isPresent())
        return this;
    else
        return predicate.test(value) ? this : empty();
}

实战示例

为null判断

之前:

if(user!=null){
    dosomething(user);
}

Optional写法:

Optional.ofNullable(user).ifPresent(u-> dosomething(u));

多层次的null判断

之前:

public String getCity(User user)  throws Exception{
    if(user!=null){
        if(user.getAddress()!=null){
            Address address = user.getAddress();
            if(address.getCity()!=null){
                return address.getCity();
            }
        }
    }
    throw new Excpetion("取值错误"); 
}

Optional写法:

public String getCity(User user) throws Exception{
    return Optional.ofNullable(user)
                   .map(u-> u.getAddress())
                   .map(a->a.getCity())
                   .orElseThrow(()->new Exception("取指错误"));
}

多层次if及else判断

之前:

public User getUser(User user) throws Exception{
    if(user!=null){
        String name = user.getName();
        if("zhangsan".equals(name)){
            return user;
        }
    }else{
        user = new User();
        user.setName("zhangsan");
        return user;
    }
}

Optional写法:

public User getUser(User user) {
    return Optional.ofNullable(user)
                   .filter(u->"zhangsan".equals(u.getName()))
                   .orElseGet(()-> {
                        User user1 = new User();
                        user1.setName("zhangsan");
                        return user1;
                   });
}

参考博客:http://www.ibloger.net/article/3209.html

正文到此结束
本文目录