加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如何为Runnable分配方法引用值

发布时间:2020-12-14 05:30:17 所属栏目:Java 来源:网络整理
导读:我讨论了 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(St
我讨论了 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也是对的.有人可以帮我理解吗

解决方法

由于 section 15.13.2 of the JLS,r2是罚款,其中包括:

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没有参数,所以没有什么可以“传递”给方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读