是否有一种方法参考方式来表达一个什么都不做的(Runnable)lambda?
Is there a method reference way to express a (Runnable) lambda that does nothing?
我有一个 AutoCloseable class,它在 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() );
要做 "something".
但是:有一种情况,什么 都不应该发生 close()
。这有效:
new Whatever( () -> {} );
如前所述,这是可行的,但我想知道:有没有办法以任何其他方式表达 "empty Runnable",例如使用某种方法引用?
第二个不带参数的构造函数怎么样?
public Whatever() {
this(() -> {});
}
然后new Whatever()
。这不是您问题的直接答案(Java 并没有这样的空操作),但它是一个有用的替代方法。
选项 1
我会用无参数版本重载构造函数。
public Whatever() {
this(() -> {});
}
() -> {}
对我来说看起来简洁明了。
选项 2
作为替代方案,您可以使用定义空 Runnable
方法
的实用程序 class
public final class EmptyUtils {
public static Runnable emptyRunnable() { return () -> {}; }
}
您可以静态导入
new Whatever(emptyRunnable());
选项 3
我觉得这个选项特别有趣(而且你要求提供方法参考)
new Whatever(EmptyRunnable::get);
尽管它需要编写一个(完全)虚拟 class
class EmptyRunnable {
public static void get() {}
}
我有一个 AutoCloseable class,它在 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() );
要做 "something".
但是:有一种情况,什么 都不应该发生 close()
。这有效:
new Whatever( () -> {} );
如前所述,这是可行的,但我想知道:有没有办法以任何其他方式表达 "empty Runnable",例如使用某种方法引用?
第二个不带参数的构造函数怎么样?
public Whatever() {
this(() -> {});
}
然后new Whatever()
。这不是您问题的直接答案(Java 并没有这样的空操作),但它是一个有用的替代方法。
选项 1
我会用无参数版本重载构造函数。
public Whatever() {
this(() -> {});
}
() -> {}
对我来说看起来简洁明了。
选项 2
作为替代方案,您可以使用定义空 Runnable
方法
public final class EmptyUtils {
public static Runnable emptyRunnable() { return () -> {}; }
}
您可以静态导入
new Whatever(emptyRunnable());
选项 3
我觉得这个选项特别有趣(而且你要求提供方法参考)
new Whatever(EmptyRunnable::get);
尽管它需要编写一个(完全)虚拟 class
class EmptyRunnable {
public static void get() {}
}