为什么我不能直接将方法引用分配给Object类型的变量? [英] Why can I not assign a method reference directly to a variable of Object type?

查看:148
本文介绍了为什么我不能直接将方法引用分配给Object类型的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于 java-8 语法的简单问题。为什么 JLS-8 限制如下表达式:

Simple question about java-8 syntax. Why does JLS-8 restrict such expressions like:

Object of_ref = Stream::of;  // compile-time error

并且仅允许以下内容:

java.util.function.Function of_ref = Stream::of;
Object obj = of_ref; // compiles ok

推荐答案

这是因为方法引用或lambda表达式的目标类型应该是一个功能接口。仅基于此,运行时将创建提供给定功能接口的实现的类的实例。将lambdas或方法引用视为 abstract 概念。将其分配给功能接口类型赋予其具体含义。

That's because the target type of a method reference or a lambda expression should be a functional interface. Based on that only, runtime will create an instance of a class providing implementation of the given functional interface. Think of lambdas or method references as abstract concept. Assigning it to a functional interface type gives it a concrete meaning.

此外,特定的lambda或方法引用可以具有多个功能接口作为其目标类型。例如,考虑以下lamda:

Moreover, a particular lambda or method reference, can have multiple functional interfaces as its target type. For example, consider the following lamda:

int x = 5;
FunctionalInterface func = (x) -> System.out.println(x);

此lambda是消费者 X 。除此之外,任何具有以下签名的抽象方法的接口:

This lambda is a Consumer of x. In addition to that, any interface with a single abstract method with following signature:

public abstract void xxx(int value);

可用作目标类型。那么,如果将lambda分配给 Object 类型,那么您希望运行时实现哪个接口?这就是为什么你要明确地提供一个功能接口作为目标类型的原因。

can be used as target type. So, which interface would you want runtime to implement, if you assign the lambda to Object type? That is why you've to explicitly provide a functional interface as target type.

现在,一旦你有一个功能接口引用持有一个实例,你可以将它分配给任何超级参考(包括对象

Now, once you got a functional interface reference holding an instance, you can assign it to any super reference (including Object)

这篇关于为什么我不能直接将方法引用分配给Object类型的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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