如何为 Runnable 分配方法引用值 [英] How assign a method reference value to Runnable
问题描述
我有一个关于 Java 8 Runnable
的问题.
I hava a problem about Java 8 Runnable
.
public static void main(String[] args) {
Runnable r1 = Test::t1;
Runnable r2 = Test::t2;
Runnable r3 = Test::t3;
}
public static void t1() {
}
public static String t2() {
return "abc";
}
public static String t3(String t) {
return t;
}
如代码所示,我明白 r1
是对的,r3
是错的,但我不明白为什么 r2
也是对的.有人能帮我理解一下吗?
As the code show, I understand r1
is right and r3
is wrong, but I don't understand why r2
is also right. Can anybody help me understand it?
推荐答案
r2
由于 JLS 的第 15.13.2 节,其中包括:
如果以下两个都为真,则方法引用表达式与函数类型一致:
A method reference expression is congruent with a function type if both of the following are true:
函数类型标识与引用对应的单个编译时声明.
The function type identifies a single compile-time declaration corresponding to the reference.
以下情况之一为真:
- 函数类型的结果为 void.
- 函数类型的结果是 R,对所选编译时声明的调用类型(第 15.12.2.6 节)的返回类型应用捕获转换(第 5.1.10 节)的结果是 R'(其中 R 是可用于推断 R') 的目标类型,并且 R 和 R' 都不为空,并且 R' 在赋值上下文中与 R 兼容.
基本上,编写 t2();
并忽略返回值是有效的,因此创建一个调用方法并忽略返回值的方法引用是有效的.
Basically, it would be valid to write t2();
and just ignore the return value, so it's valid to create a method reference which calls the method and ignores the return value.
t3
无效,因为你必须提供一个参数,而Runnable
不接受一个参数,所以没有什么可以传递"的方法.
t3
isn't valid, because you have to provide a parameter, and Runnable
doesn't take a parameter, so there'd be nothing to "pass on" to the method.
这篇关于如何为 Runnable 分配方法引用值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!