In Java, is it possible to associate some object (i.e. a String) with a function to be called ?
I have two similar menus and both have a onClickListener with some code like this:
if (item.id==0) {
doSomeFunction(argument);
}
else if (item.id==1) {
doSomeOtherFunction();
}
else if (item.id==2) {
doStuff(arg2);
}
else {
}
I would just like to have an object (i.e. Hashtable) that would allow me to define associations between “item.id” -> “code to execute”.
Example:
0 -> doSomeFunction(argument);
1 -> doSomeOtherFunction();
2 -> doStuff(arg2);
As a result I could skip these conditionals and just perform a function call of the function stored for a given item.id.
For example, with Lisp I could associate the item.id with a function and then use Lisp’s “funcall” to call that function.
Is there a standard way to do something like this in Java?
Are there alternative solutions to skip the conditionals?
Please note that the called functions may need to receive parameters.
Thanks.
Since it looks like your functions don’t need to return any values, you could associate each ID key with a
Runnableobject that calls the method you want. For example:If you need the methods to be able to return a value, you can use
Callablerather thanRunnable. You can also create your own similar interface and use it instead if needed.Currently in Java this sort of thing has to be done with an instance of a class with a single abstract method such as
Runnable. Java 7 or 8 (depending on how they decide to proceed) will add lambda expressions and method references, which I think is what you really want. Method references would allow you to do something like this (using aMap<Integer, Runnable>just like above).Edit:
Your update indicates that some of these methods would need to have arguments passed to them. However, you seem to be asking for two different things. In your example of declaring the mapping
the arguments are specified, indicating that they are either values that are available at the time you declare the mapping or they’re fields in the class or some such. In either case, you’d be able to declare them when you create the
Runnable:Here,
argumentwould either need to be a field or be declaredfinal.If, on the other hand, you don’t have references to the arguments at the time you create the mapping, you’d have to create some consistent interface that all the method calls could share. For example, the least common interface that could work for your sample would be one that declared two parameters and a
voidreturn:Then you could have:
Each
CustomRunnableonly uses the arguments that it needs, if any. Then you could do the call like this:Obviously, this is getting pretty ugly but it’s pretty much what you’d have to do in that case.