Optional 的本质,就是内部储存了一个真实的值,在构造的时候,就直接判断其值是否为空。
1、构造方法
Optional 有两个构造方法,都是 private 权限,不能由外部调用。
/**
* Constructs an empty instance.
*
* @implNote Generally only one empty instance, {@link Optional#EMPTY},
* should exist per VM.
*/
private Optional() {
this.value = null;
}
/**
* Constructs an instance with the value present.
*
* @param value the non-null value to be present
* @throws NullPointerException if value is null
*/
private Optional(T value) {
this.value = Objects.requireNonNull(value);
}
这里调用了 Objects 的方法,该方法源码如下:
/**
* Checks that the specified object reference is not {@code null}. This
* method is designed primarily for doing parameter validation in methods
* and constructors, as demonstrated below:
* <blockquote><pre>
* public Foo(Bar bar) {
* this.bar = Objects.requireNonNull(bar);
* }
* </pre></blockquote>
*
* @param obj the object reference to check for nullity
* @param <T> the type of the reference
* @return {@code obj} if not {@code null}
* @throws NullPointerException if {@code obj} is {@code null}
*/
public static <T> T requireNonNull(T obj) {
if (obj == null)
throw new NullPointerException();
return obj;
}
2、empty()
Optional类内部维护了一个 value 为 null 的对象:
/**
* Common instance for {@code empty()}.
*/
private static final Optional<?> EMPTY = new Optional<>();
而 empty
() 的作用就是返回 EMPTY 对象:
/**
* Returns an empty {@code Optional} instance. No value is present for this
* Optional.
*
* @apiNote Though it may be tempting to do so, avoid testing if an object
* is empty by comparing with {@code ==} against instances returned by
* {@code Option.empty()}. There is no guarantee that it is a singleton.
* Instead, use {@link #isPresent()}.
*
* @param <T> Type of the non-existent value
* @return an empty {@code Optional}
*/
public static<T> Optional<T> empty() {
@SuppressWarnings("unchecked")
Optional<T> t = (Optional<T>) EMPTY;
return t;
}
3、of(T value)
/**
* 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);
}
也就是说 of(T value) 函数内部调用了构造函数。根据构造函数的源码我们可以得出两个结论:
- 通过 of(T value) 函数所构造出的 Optional 对象,当 Value 值为空时,依然会报 NullPointerException。
- 通过 of(T value) 函数所构造出的 Optional 对象,当 Value 值不为空时,能正常构造 Optional 对象。
ofNullable(T 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);
}
相比较 of(T value) 的区别就是,当 value 值为 null 时,of(T value) 会报 NullPointerException 异常;ofNullable(T value) 不会 throw Exception,ofNullable(T value) 直接返回一个 EMPTY 对象。
在实际应用过程中不想隐藏 NullPointerException,这种情况下就用 of(T value) 方法,但是实际上不想隐藏 NPE 的情况少之又少。
get()
/**
* If a value is present in this {@code Optional}, returns the value,
* otherwise throws {@code NoSuchElementException}.
*
* @return the non-null value held by this {@code Optional}
* @throws NoSuchElementException if there is no value present
*
* @see Optional#isPresent()
*/
public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
获取 value。
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;
}
判断value值是否为空。
ifPresent(Consumer<? super T> consumer)
/**
* If a value is present, invoke the specified consumer with the value,
* otherwise do nothing.
*
* @param consumer block to be executed if a value is present
* @throws NullPointerException if value is present and {@code consumer} is
* null
*/
public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
consumer.accept(value);
}
相比较于 isPresent(),ifPresent(Consumer<? super T> consumer) 在 value 值不为空时,做一些操作。
filter(Predicate<? super T> predicate)
/**
* If a value is present, and the value matches the given predicate,
* return an {@code Optional} describing the value, otherwise return an
* empty {@code Optional}.
*
* @param predicate a predicate to apply to the value, if present
* @return an {@code Optional} describing the value of this {@code Optional}
* if a value is present and the value matches the given predicate,
* otherwise an empty {@code Optional}
* @throws NullPointerException if the predicate is null
*/
public Optional<T> filter(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate);
if (!isPresent())
return this;
else
return predicate.test(value) ? this : empty();
}
filter 方法接受一个 Predicate 来对 Optional 中包含的值进行过滤,如果包含的值满足条件,那么还是返回这个 Optional;否则返回 Optional.empty。
map(Function<? super T, ? extends U> mapper)
/**
* If a value is present, apply the provided mapping function to it,
* and if the result is non-null, return an {@code Optional} describing the
* result. Otherwise return an empty {@code Optional}.
*
* @apiNote This method supports post-processing on optional values, without
* the need to explicitly check for a return status. For example, the
* following code traverses a stream of file names, selects one that has
* not yet been processed, and then opens that file, returning an
* {@code Optional<FileInputStream>}:
*
* <pre>{@code
* Optional<FileInputStream> fis =
* names.stream().filter(name -> !isProcessedYet(name))
* .findFirst()
* .map(name -> new FileInputStream(name));
* }</pre>
*
* Here, {@code findFirst} returns an {@code Optional<String>}, and then
* {@code map} returns an {@code Optional<FileInputStream>} for the desired
* file if one exists.
*
* @param <U> The type of the result of the mapping function
* @param mapper a mapping function to apply to the value, if present
* @return an {@code Optional} describing the result of applying a mapping
* function to the value of this {@code Optional}, if a value is present,
* otherwise an empty {@code Optional}
* @throws NullPointerException if the mapping function is null
*/
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));
}
}
如果 User 类的结构是:
public class User {
private String name;
public String getName() {
return name;
}
}
那么获取 name 的写法如下:
String name = Optional.ofNullable(user).map(u-> u.getName()).get();
flatMap(Function<? super T, Optional<U>> mapper)
/**
* If a value is present, apply the provided {@code Optional}-bearing
* mapping function to it, return that result, otherwise return an empty
* {@code Optional}. This method is similar to {@link #map(Function)},
* but the provided mapper is one whose result is already an {@code Optional},
* and if invoked, {@code flatMap} does not wrap it with an additional
* {@code Optional}.
*
* @param <U> The type parameter to the {@code Optional} returned by
* @param mapper a mapping function to apply to the value, if present
* the mapping function
* @return the result of applying an {@code Optional}-bearing mapping
* function to the value of this {@code Optional}, if a value is present,
* otherwise an empty {@code Optional}
* @throws NullPointerException if the mapping function is null or returns
* a null result
*/
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));
}
}
相较于 map(Function<? super T, ? extends U> mapper) 而言,flatMap(Function<? super T, Optional<U>> mapper) 的唯一区别就是入参类型不同。
如果 User 类的结构是:
public class User {
private String name;
public Optional<String> getName() {
return Optional.ofNullable(name);
}
}
那么获取 name 的写法如下:
String name = Optional.ofNullable(user).flatMap(u-> u.getName()).get();
orElse(T other)
/**
* Return the value if present, otherwise return {@code other}.
*
* @param other the value to be returned if there is no value present, may
* be null
* @return the value, if present, otherwise {@code other}
*/
public T orElse(T other) {
return value != null ? value : other;
}
在构造函数传入的 value 值为 null 时,进行调用的。相当于 value 值为 null 时,给予一个默认值。用法如下:
public User createUser(){
User user = new User();
user.setName("tyy");
return user;
}
Optional.ofNullable(user).orElse(createUser());
orElseGet(Supplier<? extends T> other)
/**
* Return the value if present, otherwise invoke {@code other} and return
* the result of that invocation.
*
* @param other a {@code Supplier} whose result is returned if no value
* is present
* @return the value if present otherwise the result of {@code other.get()}
* @throws NullPointerException if value is not present and {@code other} is
* null
*/
public T orElseGet(Supplier<? extends T> other) {
return value != null ? value : other.get();
}
在构造函数传入的 value 值为 null 时,进行调用的。相当于 value 值为 null 时,给予一个默认值。用法如下:
Optional.ofNullable(user).orElseGet(() -> createUser());
orElseGet(Supplier<? extends T> other) 和 orElse(T other) 的区别在于当 user 值不为 null 时,orElse
() 依然会执行 createUser() 方法,而 orElseGet
() 并不会执行 createUser() 方法。
orElseThrow(Supplier<? extends X> exceptionSupplier)
/**
* Return the contained value, if present, otherwise throw an exception
* to be created by the provided supplier.
*
* @apiNote A method reference to the exception constructor with an empty
* argument list can be used as the supplier. For example,
* {@code IllegalStateException::new}
*
* @param <X> Type of the exception to be thrown
* @param exceptionSupplier The supplier which will return the exception to
* be thrown
* @return the present value
* @throws X if there is no value present
* @throws NullPointerException if no value is present and
* {@code exceptionSupplier} is null
*/
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
if (value != null) {
return value;
} else {
throw exceptionSupplier.get();
}
}
当 value 值为 null 时,直接抛一个异常出去,用法如下:
Optional.ofNullable(user).orElseThrow(()->new Exception("用户不存在"));
使用示例
public class User {
private String name;
private City address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public City getAddress() {
return address;
}
public void setAddress(City address) {
this.address = address;
}
}
public class City {
private String city;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
例一:
以前的写法:
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(user!=null){
dosomething(user);
}
使用 Optional 的写法:
Optional.ofNullable(user)
.ifPresent(u->{
dosomething(u);
});
例三:
以前的写法:
public User getUser(User user) throws Exception{
if(user!=null){
String name = user.getName();
if("tyy".equals(name)){
return user;
}
}else{
user = new User();
user.setName("tyy");
return user;
}
}
使用 Optional 的写法:
public User getUser(User user) {
return Optional.ofNullable(user)
.filter(u->"tyy".equals(u.getName()))
.orElseGet(()-> {
User user1 = new User();
user1.setName("tyy");
return user1;
});
}