For my Java game server I send the Action ID of the packet which basically tells the server what the packet is for. I want to map each Action ID (an integer) to a function. Is there a way of doing this without using a switch?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Another similar aproach could be using Java 8's Suppliers:
Yeah, but using an interface mean you have to create an interface for each callback which means every function you want to pass it set. Creating a delegate class to handle this gives you (not a true function pointer) but the function to be passed and if you abuse a generic to be the return type, you don't have to cast which cuts the bottleneck down to almost nothing.
The c# delegate (MultiCastDelegate to be correct) gets the info from using method MethodInfo which is the same thing you would need to do for the Delegate class using java.lang.reflect.method. I posted my code for the Delegate(T) class on another form of this site dealing with this extact issue. I make it because (yes) being from C++ I need a better way for passing functions (especially Void) then having to create an interface for on function or more. Now I can choose the function filling in the parameter information for it. Voila`! Nice and usable with no noticeable lose in speed from JIT or JVM. And if I did having only learning java programming for only a week, any java programmer can do it.
Also, it serves very well when creating a base listener and a base interface to pass in the listener. No more having to write another listener because the name of the function has changed. Creating a delegate class has great advantages as is very useable and passable.
Have you ever used Swing/AWT? Their Event hierarchy solves a similar problem. The way Java passes functions around is with an interface, for example
Then, if you want to map integers onto these objects, you could use something like a
java.util.HashMap<Integer,ActionHandler>
to manage that. The actual implementations can either go in anonymous classes (Java's best approximation of "lambda") or in proper classes somewhere. Here's the anonymous class way:(edit) If you want to be even more abusive, you can initialize the HashMap like so: