是否有可用于任何lambda的no-op(NOP)方法引用? [英] Is there a method reference for a no-op (NOP) that can be used for anything lambda?

查看:648
本文介绍了是否有可用于任何lambda的no-op(NOP)方法引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这听起来像是一个奇怪的问题,但是有没有办法引用Java 8中的Lambda的标准no-op(aka null操作,null-pattern方法,no-operation,do-nothing方法)方法。



目前,我有一个方法需要,比如 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆