public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X { if (value != null) { return value; } else { throw exceptionSupplier.get(); } }
使用示例:
package optional; import java.util.Optional; public class Snippet { public static void main(String[] args) { Optional<String> test = Optional.ofNullable(null); //这里的Lambda表达式为构造方法引用 System.out.println(test.orElseThrow(NullPointerException::new)); //将打印hello } }