gpt4 book ai didi

java - 如何将方法引用值分配给 Runnable

转载 作者:搜寻专家 更新时间:2023-10-30 21:05:11 25 4
gpt4 key购买 nike

我有一个关于 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也是对的.谁能帮我理解一下?

最佳答案

r2 由于 section 15.13.2 of the JLS 没问题,其中包括:

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.

  • One of the following is true:

    • The result of the function type is void.
    • The result of the function type is R, and the result of applying capture conversion (§5.1.10) to the return type of the invocation type (§15.12.2.6) of the chosen compile-time declaration is R' (where R is the target type that may be used to infer R'), and neither R nor R' is void, and R' is compatible with R in an assignment context.

基本上,编写 t2(); 并忽略返回值是有效的,因此创建调用方法并忽略返回值的方法引用是有效的。

t3 不是有效的,因为你必须提供一个参数,而Runnable 不是接受一个参数,所以没有什么可以“传递”给方法。

关于java - 如何将方法引用值分配给 Runnable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38118627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com