是否可以将方法存储到变量中?类似的东西
public void store() {
SomeClass foo = <getName() method>;
//...
String value = foo.call();
}
private String getName() {
return "hello";
}
我认为这可以通过 lambdas 实现,但我不知道如何。
最佳答案
是的,您可以对任何方法进行变量引用。对于简单的方法,通常使用 java.util.function.*
classes 就足够了。 .这是一个工作示例:
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
final Consumer<Integer> simpleReference = Main::someMethod;
simpleReference.accept(1);
final Consumer<Integer> another = i -> System.out.println(i);
another.accept(2);
}
private static void someMethod(int value) {
System.out.println(value);
}
}
如果您的方法与这些接口(interface)中的任何一个都不匹配,您可以定义自己的方法。唯一的要求是必须有一个抽象方法。
public class Main {
public static void main(String[] args) {
final MyInterface foo = Main::test;
final String result = foo.someMethod(1, 2, 3);
System.out.println(result);
}
private static String test(int foo, int bar, int baz) {
return "hello";
}
@FunctionalInterface // Not required, but expresses intent that this is designed
// as a lambda target
public interface MyInterface {
String someMethod(int foo, int bar, int baz);
}
}
关于java - 我可以将方法存储在 Java 8 中的变量中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29219984/