简体   繁体   English

如何使用java中可选对象的参数调用方法

[英]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));
  1. met returns nothing, and map must map the input Optional to an output Optional . met返回任何内容, map必须将输入Optional映射到输出Optional
  2. method references don't take arguments, so you should use a lambda expression. 方法引用不带参数,因此您应该使用lambda表达式。

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.

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