Optional主要是为了解决空指针异常的问题
目录
创建Optional类
of()
Optional<User> opt = Optional.of(user);
由源码可知,参数必须是存在的,不为null的,否则会抛空指针异常
/**
* Returns an {@code Optional} with the specified present non-null value.
*
* @param <T> the class of the value
* @param value the value to be present, which must be non-null
* @return an {@code Optional} with the value present
* @throws NullPointerException if value is null
*/
public static <T> Optional<T> of(T value) {
return new Optional<>(value);
}
ofNullable()
Optional<User> opt = Optional.ofNullable(user);
如果对象可能为null也可能不为null的时候,可以使用ofNullable()方法。
根据源码,我们可以看到在方法中对value参数做了处理。
/**
* Returns an {@code Optional} describing the specified value, if non-null,
* otherwise returns an empty {@code Optional}.
*
* @param <T> the class of the value
* @param value the possibly-null value to describe
* @return an {@code Optional} with a present value if the specified value
* is non-null, otherwise an empty {@code Optional}
*/
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
访问Optional对象的值
get()
Optional<User> opt = Optional.ofNullable(user);
if (opt.isPresent()){
User u = opt.get();
}
如果user为空直接get的话会报异常,所以我们需要在get之前做判断。使用isPresent进行判断。
/**
* Return {@code true} if there is a value present, otherwise {@code false}.
*
* @return {@code true} if there is a value present, otherwise {@code false}
*/
public boolean isPresent() {
return value != null;
}
orElse()
orElse()如果有值的话则返回该值,否则返回传递给它的参数值。
User user1 = new User("zxx");
User user2 = new User("lan");
User user = Optional.ofNullable(user1).orElse(user2);
System.out.println(user.getName()); //zxx
User user3 = null;
String name = Optional.ofNullable(user3).map(obj->obj.getName()).orElse("lan");
System.out.println(name); //lan
更多方法可以自行了解。