Search code examples
javajump-table

Function array in Java?


Maybe I think to much in C, but I don't see a solution how to solve this properly in java. I get a response from my server which sends a string like this:

command params <xml...>

The client receives that string and extracts the command. Now I would like to call a function which knows how to handle the command. On the C side the solution is obvious. I implemented an array with the command name and associated function pointes, so I can simply loop through the array and call the function.

Is there some way to do this on Java as well? I don't know that I could call a function based on the name. So currently I see the following options:

  1. Do a series of if(command.euqals(COMMAND)
  2. For each command I could create a separate object which I can store in an array (very messy).
  3. Use reflection, so I can have a map with the function names vs. command names.

Are there any other options?

The if statements is not the best IMO, but at least it allows for compiler errors and typechecking. Using reflection is at least more elegant because I can loop and extend it more easily, but of course, it means that I can see only runtime errors if I misstype the names.


Solution

  • Your second idea is idiomatic. Use a Map<String, Runnable> to store the command names and corresponding code, then commands.get(commandName).run() to execute one.

    Don't be afraid of creating classes! It may make your code start out more verbose, but it's much easier to write a class and never have to worry about it again than to do the same with a switch or if ... else if .... If your commands ever become more complicated than single methods (maybe toString(), undo()...), you'll be increasingly glad that you used polymorphism instead of conditionals.