Thursday, March 12, 2009

Passing Functions in Java

Though it is not possible to pass functions in java like in dynamic languages, you can just as easily create a new class and pass that class with the given with a defined function. The method can even take arguments and return a value given by parameterized types. Below is the interface I created that these classes implement which contain the function you want to call.


package com.ucc.csd.client.common;
public interface FunctionCall {
V call(T value);
}


V is used to specify the class that needs to be returned by the method, and T is used to specify the class that the method takes. These can easily just be of type Void if no value needs to be passed or returned. Below is an example that doesn't need to take or return values.


public class SomeClass{

private void doSomething(){

FunctionCall callOnCompletion = new FunctionCall()
{
public Void call(Void arg0)
{
//do stuff

return null;
}
};

SomeCommonClass.doStuff(callOnCompletion);
}
}

public class SomeCommonClass{

static void doStuff(FunctionCall callOnCompletion){
//do stuff

callOnCompletion.call(null);
}
}