How can I store a method in a variable in Java 8?
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);
}
}
You can use Java 8 method references. You can use the ::
'operator' to grab a method reference from an object.
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
}
}
You just need a @FunctionalInterface
that matches the signature of the method you want to store. java.util.function
contains a selection of the most commonly used ones.