[英]How to call a method with parameters from an optional object in java
Let's consider the following class 我们来考虑以下课程
class A{
void met(int i){
//do somthing
}
}
and let's consider that we have an optional object of this class like: 让我们考虑一下这个类的可选对象,如:
Optional<A> a;
is it possible to call the method met
on the object a
without the need to check whether a
refers to a full object or just empty ( null
). 是否可以在对象a
上调用met
方法,而无需检查a
是引用完整对象还是只是空( null
)。 Something like: 就像是:
a.map(A::met(5));
Unfortunately this code doesn't compile. 不幸的是,这段代码无法编译。 How can this be done? 如何才能做到这一点?
There are two reasons why this can't work: 这有两个原因:
a.map(A::met(5));
met
returns nothing, and map
must map the input Optional
to an output Optional
. met
返回任何内容, map
必须将输入Optional
映射到输出Optional
。 What you need is : 你需要的是:
a.ifPresent(x->x.met(5));
Another option : 另外一个选项 :
a.orElse(new A()).met(5);
This will execute met(5)
on a dummy instance if a
is empty, so it's probably not the best way. 如果a
为空,这将在虚拟实例上执行met(5)
,因此它可能不是最好的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.