如何在 Java 8 中将方法存储在变量中? [英] How can I store a method in a variable in Java 8?
本文介绍了如何在 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屋!
查看全文