在Java8中如何将方法存储在变量中?

在Java8中如何将方法存储在变量中?,java,lambda,java-8,Java,Lambda,Java 8,是否可以将方法存储到变量中?差不多 public void store() { SomeClass foo = <getName() method>; //... String value = foo.call(); } private String getName() { return "hello"; } 公共作废存储(){ SomeClass foo=; //... 字符串值=foo.call(); } 私

是否可以将方法存储到变量中?差不多

 public void store() {
     SomeClass foo = <getName() method>;
     //...
     String value = foo.call();
 }

 private String getName() {
     return "hello";
 }
公共作废存储(){
SomeClass foo=;
//...
字符串值=foo.call();
}
私有字符串getName(){
回复“你好”;
}

我认为这在lambdas中是可能的,但我不知道如何实现。

您可以使用方法引用,如-

System.out::println  
这相当于lambda表达式-

x -> System.out.println(x).  

此外,您可以使用用户反射来存储方法,它也适用于早期版本的
java

您可以使用Java8方法引用。您可以使用
::
“运算符”从对象获取方法引用

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
    }
}

您只需要一个与要存储的方法的签名相匹配的
@functioninterface
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);
    }
}