Optional.of(null)将抛出NPE,我需要在调用该方法之前验证null吗? [英] Optional.of(null)will throw NPE, I need to verify null before call the method?
问题描述
Java 8引入了Optional处理NPE.在实际应用中,我无法理解问题.
Java 8 introduces Optional to deal with NPE. In practical application,I can‘t understand a problem.
我有方法A
public void doSomethingA(String para) {
Optional<String> name = Optional.of(para);
if (name.isPresent()) {
//do
}
}
但是如果para = null,它将抛出NPE.
But if para = null, it will throw NPE.
方法B
public void doSomethingB(String para) {
if (para != null) {
//do
}
}
如果我检查para不为null,那么A和B有什么区别.
if I check para is not null, What's the difference between A and B.
可选"的含义在哪里.
推荐答案
使用使用 Optional.of
如果您知道自己有一个非空值,或者如果抛出NullPointerException
则可以,则可以.
Use Optional.of
if you know you have a non-null-value or if it's ok for you if a NullPointerException
is thrown otherwise.
关于其余问题:为什么选择null
或Optional
,您可能会发现以下问题有用:
Regarding the rest of your question: why null
or Optional
you may find the following question useful: Optional vs. null. What is the purpose of Optional in Java 8?
您的问题还可能与以下内容有关:为什么要使用Optional.of over Optional .ofNullable?
Your question may also be related to: Why use Optional.of over Optional.ofNullable?
这篇关于Optional.of(null)将抛出NPE,我需要在调用该方法之前验证null吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!