views:

135

answers:

2

Hello folks,

When programming with C/C++ or Python I sometimes used to have a dictionary with references to functions according to the specified keys. However, I don't really know how to have the same -- or at the very least similar -- behavior in Java allowing me dynamic key-function (or method, in Java slang) association.

Also, I did find the HashMap technique somebody suggested, but is that seriously the best and most elegant way? I mean, it seems like a lot to create a new class for every method I want to use.

I'd really appreciate every input on this.

+1  A: 

The short answer is you need to wrap each method in a class - called a functor.

Draemon
Apache Commons Functor exists to provide this in Java - http://commons.apache.org/sandbox/functor/. Stuff that in your HashMap :)
Jon
+10  A: 

You don't need to create a full, name class for each action. You can use anonymous inner classes:

public interface Action<T>
{
    void execute(T item);
}

private static Map<String, Action<Foo>> getActions()
{
    Action<Foo> firstAction = new Action<Foo>() {
        @Override public void execute(Foo item) {
             // Insert implementation here
        }
    };
    Action<Foo> secondAction = new Action<Foo>() {
        @Override public void execute(Foo item) {
             // Insert implementation here
        }
    };
    Action<Foo> thirdAction = new Action<Foo>() {
        @Override public void execute(Foo item) {
             // Insert implementation here
        }
    };
    Map<String, Action<Foo>> actions = new HashMap<String, Action<Foo>>();
    actions.put("first", firstAction);
    actions.put("second", secondAction);
    actions.put("third", thirdAction);
    return actions;
}

(Then store it in a static variable.)

Okay, so it's not nearly as convenient as a lambda expression, but it's not too bad.

Jon Skeet
Execute should be execute, as Java naming conventions recommends
dfa
@dfa: Cheers - that's what I get for mixing a .NET delegate name with a Java interface :)
Jon Skeet