Is it possible to store a method into a variable? Something like
public void store() {
SomeClass foo = ;
//...
String
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.