为什么此Java 8方法参考进行编译? [英] Why does this Java 8 method reference compile?

查看:65
本文介绍了为什么此Java 8方法参考进行编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在更深入地研究 Java 8 功能,例如Lambda和方法引用.玩一会儿,使我进入了以下示例:

I'm currently diving deeper into Java 8 features like Lambdas and method references. Playing around a bit brought me to the following example:

public class ConsumerTest {

  private static final String[] NAMES = {"Tony", "Bruce", "Steve", "Thor"};

   public static void main(String[] args) {
      Arrays.asList(NAMES).forEach(Objects::requireNonNull);
   }
}

我的问题是:

为什么main方法内的行会编译?

Why does the line inside the main method compile ?

如果我正确理解这件事,则引用方法的签名必须与功能接口的SAM签名相对应.在这种情况下,消费者需要以下签名:

If I understood the thing correctly, the referenced method's signature has to correspond to the functional interface's SAM signature. In this case, the Consumer requires the following signature:

void accept(T t);

但是, requireNonNull 方法返回 T 而不是void:

However, the requireNonNull method returns T instead of void:

public static <T> T requireNonNull(T obj)

推荐答案

Java语言规范版本8在

The Java Language Specification version 8 says in 15.13.2:

如果T是功能接口类型(

A method reference expression is compatible in an assignment context, invocation context, or casting context with a target type T if T is a functional interface type (§9.8) and the expression is congruent with the function type of the ground target type derived from T.

[..]

如果满足以下两个条件,则方法引用表达式与函数类型一致:

A method reference expression is congruent with a function type if both of the following are true:

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