reflection - Instantiate class dynamically based on some constant in Java -
i making multiplayer game makes heavy use of serialisable event
class send messages on network. want able reconstruct appropriate subclass of event
based on constant.
so far have opted following solution:
public class eventfactory { public static event getevent(int eventid, bytebuffer buf) { switch (eventid){ case event.id_a: return eventa.deserialise(buf); case event.id_b: return eventb.deserialise(buf); case event.id_c: return eventc.deserialise(buf); default: // unknown event id return null; } } }
however, strikes me being verbose , involves adding new 'case' statement every time create new event
type.
i aware of 2 other ways of accomplishing this, neither seems better*:
- create mapping of constants -> event subclasses, , use clazz.newinstance() instantiate them (using empty constructor), followed clazz.initialiase(buf) supply necessary parameters.
- create mapping of constants -> event subclasses, , use reflection find , call right method in appropriate class.
is there better approach 1 using? perhaps unwise disregard alternatives mentioned above?
*note: in case better means simpler / cleaner without compromising on speed.
you can use hashmap<integer,event>
correct event eventid. adding or removing events going easy, , code grows easy maintain when compared switch case solution , speed wise should faster switch case solution.
static { hashmap<integer,event> eventhandlermap = new hashmap<>(); eventhandlermap.put(eventid_a, new eventhandlera()); eventhandlermap.put(eventid_b, new eventhandlerb()); ............ }
instead of switch statement can use :
event event = eventhandlermap.get(eventid); if(event!=null){ event.deserialise(buf); }
Comments
Post a Comment