orElseGet解决空指针问题
这没问题
NamedSql namedSql=new NamedSql();
String s = Optional.ofNullable(namedSql).map(a -> a.getCode()).orElseGet(()->null);
System.out.println("Optional 输出是:"+s); //输出null
这就报空指针了:
NamedSql namedSql=new NamedSql();
String s = Optional.ofNullable(namedSql).map(a -> a.getCode()).orElseGet(null);
System.out.println("Optional 输出是:"+s);
输出:
查看Optional中orElseGet方法源码 :
/**
* 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();** **null.方法 就报空指针**
}