是否有可用于任何lambda的no-op(NOP)方法引用? [英] Is there a method reference for a no-op (NOP) that can be used for anything lambda?
问题描述
目前,我有一个方法需要,比如 void foo(Consumer< Object>)
,并且我想给它一个no-op,我必须声明:
foo(new Consumer< Object>(){
public void accept(Object o){
// do not
}
}
我希望能够做到这样的事情:
foo(Object :: null)
取而代之。是否存在类似的东西?
不知道这将如何与多参数方法一起工作 - 也许这是Java中lambda表达式的一个缺陷。
这是没有缺陷的。 Java中的Lambdas是函数接口的实例;它们在tur n,抽象为可以简化为单个抽象方法或SAM的Java结构的实例。
但是这个SAM仍然需要有一个有效的原型。在你的情况下,你希望有一个无操作 Consumer< T>
,它不会做任何事情,不管 T
/ p>
然而,它仍然需要是 Consumer< T>
这意味着您可以创建的最小声明为:
private static final Consumer< Object> NOOP =无论 - > {};
并使用 NOOP
在需要的地方。
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.
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?
Not sure how that would work with multi-parameter methods -- perhaps this is a deficiency in the lambdas in Java.
This is no deficiency.
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.
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
.
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 -> {};
and use NOOP
where you need to.
这篇关于是否有可用于任何lambda的no-op(NOP)方法引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!