gpt4 book ai didi

Java 8 : Is it possible to assign a method reference to a variable?

转载 作者:行者123 更新时间:2023-12-03 19:10:21 25 4
gpt4 key购买 nike

我用 Google 搜索了这个问题的答案,但找不到。

在 Java 8 中,我知道这是可能的:

// someMethod is defined as: someMethod(AFunctionalInterface i)
someMethod(someObject::someOtherMethod);

问题是:是否可以做到以下几点

AFunctionalInterface i = anObject::SomeMethod;

此外,是否可以将 lambda 赋值给变量并像这样传递它?

打印机 f = () -> System.out.println(..); methodThatTakesPrinter(f);

最佳答案

是的,根据 JLS 中引用的示例,这是可能的:

Task t = () -> System.out.println("hi");
Runnable r = t::invoke;

此外,声明如下:

A method reference expression is compatible in an assignment context [emphasis mine], 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.

关于Java 8 : Is it possible to assign a method reference to a variable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25776595/

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