【问题标题】:Is there a method reference way to express a (Runnable) lambda that does nothing?有没有一种方法引用方式来表达一个什么都不做的(可运行的)lambda?
【发布时间】:2019-08-23 07:53:57
【问题描述】:

我有一个 AutoCloseable 类,它在 close() 内执行一个 Runnable,如下所示:

static class Whatever implements AutoCloseable {
    Runnable r;
    public Whatever(Runnable r) {
        this.r = r;
    }

    @Override
    public void close() throws Exception {
        r.run();
    }
}

@Test
public void testAutoClose() throws Exception {
    List<Boolean> updateMe = Arrays.asList(false);
    AutoCloseable ac = new Whatever(() -> updateMe.set(0, true));
    ac.close();
    assertThat("close() failed to update list", updateMe, is(Collections.singletonList(true)));
}

上面的效果很好。并让我拥有像

这样的代码
new Whatever( () -> foo() );

做“某事”。

但是:有一种情况,对于close()什么都不应该发生。这有效:

new Whatever( () -> {} ); 

如前所述,这可以完成工作,但我想知道:有没有办法以任何其他方式表达“空 Runnable”,例如使用某种方法引用?

【问题讨论】:

  • This 可能会有所帮助
  • @michalk 不,确实有帮助。
  • @GhostCat 使用方法参考选项更新了答案。你可能会喜欢。

标签: java lambda method-reference


【解决方案1】:

选项 1

我会用无参数版本重载构造函数。

public Whatever() {
    this(() -> {}); 
}

() -&gt; {} 在我看来简洁明了。

选项 2

作为替代方案,您可以使用定义空 Runnable 方法的实用程序类

public final class EmptyUtils {
    public static Runnable emptyRunnable() { return () -> {}; }
}

你可以静态导入的

new Whatever(emptyRunnable());

选项 3

我觉得这个选项特别有趣(并且您要求提供方法参考)

new Whatever(EmptyRunnable::get);

即使它需要编写一个(完全)虚拟类

class EmptyRunnable {
    public static void get() {}
}

【讨论】:

    【解决方案2】:

    第二个不带参数的构造函数怎么样?

    public Whatever() {
        this(() -> {});
    }
    

    然后只需执行new Whatever()。这不是您问题的直接答案(Java 并没有真正的无操作),但它是一个有用的替代方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 2011-11-08
      • 2011-12-28
      • 2023-03-27
      • 1970-01-01
      • 2019-06-30
      • 2019-11-04
      相关资源
      最近更新 更多