是否有可用于任何 lambda 的无操作 (NOP) 的方法参考? [英] Is there a method reference for a no-op (NOP) that can be used for anything lambda?
问题描述
这听起来可能是一个奇怪的问题,但是有没有办法在 Java 8 中引用 Lambda 的标准无操作(又名空操作、空模式方法、无操作、无操作方法)方法.
This may sounds like a strange question, but is there a way to refer to a standard no-op (aka null operation, null-pattern method, no-operation, do-nothing method) method for a Lambda in Java 8.
目前,我有一个方法,例如,void foo(Consumer
,我想给它一个空操作,我必须声明:
Currently, I have a method that takes a, say, void foo(Consumer<Object>)
, and I want to give it a no-op, I have to declare:
foo(new Consumer<Object>() {
public void accept(Object o) {
// do nothing
}
}
我希望能够执行以下操作:
where I would like to be able to do something like:
foo(Object::null)
相反.类似的东西存在吗?
instead. Does something like exist?
不确定这将如何与多参数方法一起使用 -- 也许这是 Java 中 lambdas 的一个缺陷.
Not sure how that would work with multi-parameter methods -- perhaps this is a deficiency in the lambdas in Java.
推荐答案
这不是缺陷.
Java 中的 Lambda 是函数式接口的实例;反过来,它们被抽象为 Java 结构的实例,这些实例可以简化为一个单个抽象方法或 SAM.
Lambdas in Java are instances of functional interfaces; which, in turn, are abstracted to instances of Java constructs which can be simplified to one single abstract method, or SAM.
但是这个 SAM 仍然需要有一个有效的原型.在您的情况下,您希望有一个无操作 Consumer
什么都不做,T
.
But this SAM still needs to have a valid prototype. In your case, you want to have a no-op Consumer<T>
which does nothing whatever the T
.
它仍然需要是一个Consumer
;这意味着您可以提出的最小声明是:
It still needs to be a Consumer<T>
however; which means the minimal declaration you can come up with is:
private static final Consumer<Object> NOOP = whatever -> {};
并在需要的地方使用 NOOP
.
and use NOOP
where you need to.
这篇关于是否有可用于任何 lambda 的无操作 (NOP) 的方法参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!