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);
}
}


As an Amazon Associate I earn from qualifying purchases.

My favorite quotations..


“A man should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts, build a wall, set a bone, comfort the dying, take orders, give orders, cooperate, act alone, solve equations, analyze a new problem, pitch manure, program a computer, cook a tasty meal, fight efficiently, die gallantly. Specialization is for insects.”  by Robert A. Heinlein

"We are but habits and memories we chose to carry along." ~ Uki D. Lucas


Popular Recent Articles