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.

No comments:

Post a Comment

Post Scriptum

The views in this article are mine and do not reflect those of my employer.
I am preparing to cancel the subscription to the e-mail newsletter that sends my articles.
Follow me on:
X.com (Twitter)
LinkedIn
Google Scholar

Popular Recent Posts

Most Popular Articles

apt quotation..