关于Optional orElseGet的一些注意点

orElseGet 解决空指针问题

如何解决

1
2
3
  NamedSql namedSql=new NamedSql();
  String s = Optional.ofNullable(namedSql).map(a -> a.getCode()).orElseGet(()->null);
  System.out.println("Optional 输出是:"+s);  //输出null

爆出空指针的代码如下:

1
2
3
  NamedSql namedSql=new NamedSql();
  String s = Optional.ofNullable(namedSql).map(a -> a.getCode()).orElseGet(null);
  System.out.println("Optional 输出是:"+s);

本着如何会出现这样的问题

image-20230428153252822

查看 Optional 中 orElseGet 方法源码 :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
    /**
     * If a value is present, returns the value, otherwise returns the result
     * produced by the supplying function.
     *
     * @param supplier the supplying function that produces a value to be returned
     * @return the value, if present, otherwise the result produced by the
     *         supplying function
     * @throws NullPointerException if no value is present and the supplying
     *         function is {@code null}
     */
    public T orElseGet(Supplier<? extends T> supplier) {
        return value != null ? value : supplier.get();
    }

报错是因为 get 方法爆出来的。

Licensed under CC BY-NC-SA 4.0
最后更新于 Jan 06, 2025 05:52 UTC
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计
Caret Up