Java 源码 - Optional 类


介绍

A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

示例

public class Test {
  public static void main(String[] args) {
    String name = Optional.ofNullable("feigege").map(u -> u.toUpperCase()).orElse("为空");
    System.out.println(name);  // FEIGEGE
  }
}

源码

成员变量

/**
 * If non-null, the value; if null, indicates no value is present.
 */
private final T value;

/**
 * Common instance for empty().
 */
private static final Optional<?> EMPTY = new Optional<>();

构造方法

/**
 * Constructs an instance with the value present.
 */
private Optional(T value) {
  this.value = Objects.requireNonNull(value);
}

成员方法

/**
 * Returns an Optional describing the specified value, if non-null,
 * otherwise returns an empty Optional.
 */
public static  Optional ofNullable(T value) {
  return value == null ? empty() : of(value);
}

/**
 * Returns an Optional with the specified present non-null value.
 */
public static  Optional of(T value) {
  return new Optional<>(value);
}

/**
 * Returns an empty Optional instance. No value is present for this Optional.
 */
public static Optional empty() {
  @SuppressWarnings("unchecked")
  Optional t = (Optional) EMPTY;
  return t;
}

/**
 * Return true if there is a value present, otherwise false.
 */
public boolean isPresent() {
    return value != null;
}
    
/**
 * If a value is present in this Optional, returns the value,
 * otherwise throws NoSuchElementException.
 */
public T get() {
  if (value == null) {
    throw new NoSuchElementException("No value present");
  }
}   

面试

Optional 类的好处?
使用 Optional 类可以优雅的处理 null 值,采用链式编程的风格,可以帮助我们顺着一口气写完代码逻辑,在途中无需进行进行一层层判断是否为空。