在使用Java 8可选类时,有两种方法可以将值包装在可选类中。

String foobar = <value or null>;
Optional.of(foobar);         // May throw NullPointerException
Optional.ofNullable(foobar); // Safe from NullPointerException

我明白可选的。ofNullable是唯一安全的使用Optional的方式,但是为什么Optional。存在吗?为什么不直接使用Optional呢?nullable和在任何时候都是安全的?


Your question is based on assumption that the code which may throw NullPointerException is worse than the code which may not. This assumption is wrong. If you expect that your foobar is never null due to the program logic, it's much better to use Optional.of(foobar) as you will see a NullPointerException which will indicate that your program has a bug. If you use Optional.ofNullable(foobar) and the foobar happens to be null due to the bug, then your program will silently continue working incorrectly, which may be a bigger disaster. This way an error may occur much later and it would be much harder to understand at which point it went wrong.


此外,如果你知道你的代码在object为空时不应该工作,你可以使用option . orelsethrow抛出异常

String nullName = null;

String name = Optional.ofNullable(nullName)
                      .orElseThrow(NullPointerException::new);
                   // .orElseThrow(CustomException::new);

不管怎样,Optional应该主要用于Services的结果。在服务中,你知道你手头有什么,如果你有一个结果,返回option .of(someValue),如果你没有,返回option .empty()。在这种情况下,someValue永远不应该为空,并且仍然返回一个Optional。


这取决于具体情况。

假设您有一些业务功能,您需要进一步处理具有该值的内容,但在处理时使用空值会影响它。

在这种情况下,您可以使用Optional<?>。

String nullName = null;

String name = Optional.ofNullable(nullName)
                      .map(<doSomething>)
                      .orElse("Default value in case of null");

主要差异b/w可选。的和可选的。ofNullable是如果包裹在Optional下的元素为null,则为Optional。的值将引发空指针异常,并停止对代码的进一步处理。然而,可选的。ofNullable将忽略null元素/对象,并返回Optional.empty()或NoSuchElementPresent。