Is there a way to pass a call back function in a Java method?
The behavior I'm trying to mimic is a .Net Delegate being passed to a function.
I've seen people suggesting creating a separate object but that seems overkill, however I am aware that sometimes overkill is the only way to do things.
Check the closures how they have been implemented in the lambdaj library. They actually have a behavior very similar to C# delegates:
http://code.google.com/p/lambdaj/wiki/Closures
When I need this kind of functionality in Java, I usually use the Observer pattern. It does imply an extra object, but I think it's a clean way to go, and is a widely understood pattern, which helps with code readability.
I think using an abstract class is more elegant, like this:
I tried using java.lang.reflect to implement 'callback', here's a sample:
Since Java 8, there are lambda and method references:
For example, lets define:
and
Then you can do:
You can find an example on github, here: julien-diener/MethodReference.
it's a bit old, but nevertheless... I found the answer of Peter Wilkinson nice except for the fact that it does not work for primitive types like int/Integer. The problem is the
.getClass()
for theparameters[i]
, which returns for instancejava.lang.Integer
, which on the other hand will not be correctly interpreted bygetMethod(methodName,parameters[])
(Java's fault) ...I combined it with the suggestion of Daniel Spiewak (in his answer to this); steps to success included: catching
NoSuchMethodException
->getMethods()
-> looking for the matching one bymethod.getName()
-> and then explicitly looping through the list of parameters and applying Daniels solution, such identifying the type matches and the signature matches.