如何在Java 8中将方法存储在变量中? [英] How can I store a method in a variable in Java 8?

查看:90
本文介绍了如何在Java 8中将方法存储在变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to store a method into a variable? Something like

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

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

我认为lambdas可以实现,但我不知道怎么做.

I think this is possible with lambdas but I don't know how.

推荐答案

是的,您可以具有对任何方法的变量引用.对于简单的方法,通常使用 java.util.function.*.这是一个工作示例:

Yes, you can have a variable reference to any method. For simple methods it's usually enough to use java.util.function.* classes. Here's a working example:

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

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

If your method does not match any of those interfaces, you can define your own. The only requirement is that is must have a single abstract method.

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中将方法存储在变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆