gpt4 book ai didi

java - 是否有一种方法引用方式来表达一个什么都不做的(Runnable)lambda?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:37:10 24 4
gpt4 key购买 nike

我有一个 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”,例如使用某种方法引用?

最佳答案

选项 1

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

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

() -> {} 对我来说看起来简洁明了。

选项 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() {}
}

关于java - 是否有一种方法引用方式来表达一个什么都不做的(Runnable)lambda?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57621964/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com