There is no equivalent to c++ function pointers in Java. Which means that it is not possible to pass a method as a parameter to another method (unless reflection is used but I wont go there)… you can pass an interface instead though.

For example – given two different methods add and multiply:

int add(int f1, int f2){
return f1+f2;
}
int multiply(int f1, int f2){
return f1*f2;
}

…and a method which accepts a Calculator interface as its parameter

interface Calculator {
public int calculate(int i,int j);
}
void recordCalc(Calculator calculator, int i, int j){
int result =calculator.calculate(i,j);
//...store the result on disk
}

then passing add(i,j) or multiply(i,j) as a parameter to the recordCalc method is done like so:

Calculator add = new Calculator(){
@Override
public int calculate(int i, int j) {
return add(i,j);
}
} ;
Calculator multiply = new Calculator(){
@Override
public int calculate(int i, int j) {
return multiply(i,j);
}
} ;
recordCalc(multiply,3,3);
recordCalc(add,5,5);

ie. we create two anonymous classes, each implementing Calculator in their own way, which are then passed to the recordCalc method as an interface. It is a bit ugly there’s no denying it.

Enter stage left: Java 8 with lambda support. A lambda is basically a very compact way to implement anonymous classes. They’re represented using an arrow “->”, like so:

Calculator add = (i, j) -> add(i,j);
Calculator multiply = (i, j) -> multiply(i, j);
recordCalc(multiply, 3, 3);
recordCalc(add, 5, 5);

or even simpler

recordCalc((i, j) -> add(i,j), 3, 3);
recordCalc((i, j) -> multiply(i, j), 5, 5);

The initial 16 lines of code implementation using anonymous classes is now reduced to a 2-liner. Shame it’s another 6 months to wait before Java 8 is officially released.

Finally – if you’re using IntelliJ an anonymous class can be transformed into a lambda with one click of the mouse:

### Like this:

Like Loading...

*Related*