我可以在 Java 8 中将方法存储在变量中吗?

新手上路,请多包涵

是否可以将方法存储到变量中?就像是

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

 private String getName() {
     return "hello";
 }

我认为 lambda 可以做到这一点,但我不知道如何做到。

原文由 fangio 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 367
2 个回答

是的,您可以拥有对任何方法的变量引用。对于简单的方法,通常使用 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);
    }
}

如果您的方法与这些接口中的任何一个都不匹配,您可以定义自己的方法。唯一的要求是必须有一个抽象方法。

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

原文由 esin88 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用 Java 8 方法引用。您可以使用 :: ‘operator’ 从对象中获取方法引用。

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

您只需要一个 @FunctionalInterface 与您要存储的方法的签名相匹配。 java.util.function 包含一些最常用的选项。

原文由 axblount 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题