简体   繁体   English

在这种情况下如何使用Guava Optional

[英]How to use Guava Optional in this scenario

I have a scenario which I want to use Guava Optional, but there is problem: 我有一个想使用Guava Optional的场景,但是有问题:

The method is like this: 方法是这样的:

private static void method(Optional<Object> myOptional) {
   if(myOptional.isPresent()) {
       ....
   }
}

The myOptional can contain non-null value, null value, or absent(). myOptional可以包含非null值,null值或absent()。 A null is a valid input in this scenario. 在这种情况下,null是有效输入。

In the method, I want to process non-null value and null value using differnt ways, but ignore absent value. 在该方法中,我想使用不同的方式处理非null值和null值,但忽略不存在的值。

However, if I use isPresent here, the null value will be ignored as well. 但是,如果我在此处使用isPresent,则null值也将被忽略。 But if I use "get" method, the absent value will throw exception. 但是,如果我使用“ get”方法,则缺少的值将引发异常。 If I use orNull, the absent value also returns as null. 如果我使用orNull,则缺少的值也将返回null。

I am not sure what I shall do here. 我不知道该怎么办。 But I think the reason to create Optional is to differentiate null and absent so that null becomes a valid meaningful value. 但是我认为创建Optional的原因是区分null和不存在,以便null成为有效的有意义的值。 But it looks like there is no method in Optional that allows me to achieve my usecase. 但是,看起来Optional中没有方法可以实现用例。

Can anyone help? 有人可以帮忙吗? Thanks. 谢谢。

You can't do that. 你不能那样做。

The javadoc says it explicitly: an Optional may contain a non null reference . javadoc明确表示: Optional可以包含非null引用 Never a null one. 从来没有一个null

What you can do is create an Optional.fromNullable(whatever).orNull() . 您可以做的是创建一个Optional.fromNullable(whatever).orNull() But an Optional will never differentiate a null value from absent, since it is not what it is meant to do! 但是Optional决不会将空值与不存在的值区分开,因为这不是它的本意!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM