如何在Java 8中的变量中存储方法?
是否可以将方法存储到变量中?类似的东西
 public void store() {
     SomeClass foo = <getName() method>;
     //...
     String value = foo.call();
 }
 private String getName() {
     return "hello";
 }
我认为这在lambdas是可能的,但我不知道如何。
是否可以将方法存储到变量中?类似的东西
 public void store() {
     SomeClass foo = <getName() method>;
     //...
     String value = foo.call();
 }
 private String getName() {
     return "hello";
 }
我认为这在lambdas是可能的,但我不知道如何。
是的,您可以对任何方法进行变量引用。对于简单的方法,通常使用java.util.function.*类就足够了。下面是一个工作示例:
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);
    }
}
如果您的方法与这些接口中的任何一个都不匹配,则可以定义自己的接口。唯一的要求是必须具有单个抽象方法。
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 8 方法引用。可以使用“运算符”从对象中获取方法引用。::
import java.util.function.IntConsumer;
class Test {
    private int i;
    public Test() { this.i = 0; }
    public void inc(int x) { this.i += x; }
    public int get() { return this.i; }
    public static void main(String[] args) {
        Test t = new Test();
        IntConsumer c = t::inc;
        c.accept(3);
        System.out.println(t.get());
        // prints 3
    }
}
您只需要与要存储的方法的签名匹配的。 包含一系列最常用的。@FunctionalInterfacejava.util.function