【发布时间】: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