views:

6946

answers:

6

Is there a way to do pass a call back function in a Java method?

The bahaviour I'm trying to mimic is a .Net Delegate being passed to a function.

I've seem people suggesting creating a separate object but that seems overkill, however I am aware that sometimes overkill is the only way to do things.

+9  A: 

You can use an interface. See here: http://www.javaworld.com/javaworld/javatips/jw-javatip10.html

Alex

Alex Fort
+11  A: 

If you mean somthing like .NET anonymous delegate, I think Java's anonymous class can be used as well.

public class Main {

    public interface Visitor{
        int DoJob(int a, int b);
    }


    public static void main(String[] args) {
        Visitor adder = new Visitor(){
            public int DoJob(int a, int b) {
                return a + b;
            }
        };

        Visitor multiplier = new Visitor(){
            public int DoJob(int a, int b) {
                return a*b;
            }
        };

        System.out.println(adder.DoJob(10, 20));
        System.out.println(multiplier.DoJob(10, 20));

    }
}
m3rLinEz
This is the canonical method since Java 1.0.
Charlie Martin
I've been usign this, it's slioghtly more verbose than what I'd like, but it works.
Omar Kooheji
+1  A: 
erickson
"A method is not (yet) a first-class object in Java" -- well, there's the method class[1], of which you can certainly pass around instances. It's not the clean, idiomatic, OO code that you'd expect from java, but it might be expedient. Certainly something to consider, though.[1] http://java.sun.com/j2se/1.4.2/docs/api/java/lang/reflect/Method.html
Jonas Kölker
+1  A: 

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.

MattK
A: 

A little nitpicking:

I've seem people suggesting creating a separate object but that seems overkill

Passing a callback includes creating a separate object in pretty much any OO language, so it can hardly be considered overkill. What you probably mean is that in Java, it requires you to create a separate class, which is more verbose (and more resource-intensive) than in languages with explicit first-class functions or closures. However, anonymous classes at least reduce the verbosity and can be used inline.

Michael Borgwardt
Yes that is what i meant. With 30 or so events you end up with 30 classes.
Omar Kooheji
A: 

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

Mario Fusco