Function pointers/delegates in Java?
Another similar approach could be using Java 8's Suppliers:
Map<Integer, Supplier<T>> suppliers = new HashMap();
suppliers.put(1, () -> methodOne());
suppliers.put(2, () -> methodTwo());
// ...
public T methodOne() { ... }
public T methodTwo() { ... }
// ...
T obj = suppliers.get(id).run();
What about this one?
HashMap<Integer, Runnable> map = new HashMap<Integer, Runnable>();
map.put(Register.ID, new Runnable() {
public void run() { functionA(); }
});
map.put(NotifyMessage.ID, new Runnable() {
public void run() { functionB(); }
});
// ...
map.get(id).run();
(If you need to pass some arguments, define your own interface with a function having a suitable parameter, and use that instead of Runnable).
Java does not have first-class function pointers. In order to achieve similar functionality, you have to define and implement an interface. You can make it easier using anonymous inner classes, but it's still not very pretty. Here's an example:
public interface PacketProcessor
{
public void processPacket(Packet packet);
}
...
PacketProcessor doThing1 = new PacketProcessor()
{
public void processPacket(Packet packet)
{
// do thing 1
}
};
// etc.
// Now doThing1, doThing2 can be used like function pointers for a function taking a
// Packet and returning void
Java doesn't really have function pointers (we got anonymous inner classes instead). There's really nothing wrong with using a switch, though, as long as you're switching on value and not on type. Is there some reason you don't want to use a switch? It seems like you'll have to do a mapping between Action IDs and actions somewhere in your code, so why not keep it simple?