java - Creating Complex Objects from ResultSet -


sqlite , java beginner here,

i'm working on game player obtains random items, since plan on including huge amount of items, have stored item information in sqlite db.

the thing is, item objects have own behavior objects in addition fields string name, int power, etc. makes converting results objects more complicated endeavor. referring these behaviors strings in db, , instantiating correct behavior object using switch statement @ item creation. semi-fictional example show mean:

item item = new item();  string name = resultset.getstring("name"); string activationeffect = resultset.getstring("activation effect");  item.setname(name);  switch (activationeffect){     case "smack fools":         item.setactivationeffect(new smackfools());         break;     case "have nap":         item.setactivationeffect(new naptime());         break;     default:         break; 

alternatively make item.setactivationeffect take string , switch statement itself, doesn't change anything. there better way accomplish this?

you need way relate each behaviour name (a string) class (to create new object of class). since behaviour names not equal classes name can't directly use reflection that.
there no way around it, have make table.
there many ways such table, yours switches valid one. though don't verbosity; need 3 lines each new behaviour.

in following code of isolated in class.
need add single line each time add new behaviour.
assuming behaviours extend common activationeffect class, or implement common activationeffect interface.

class activationeffectsfactory {     private static map<string, class<? extends activationeffect>> map = new hashmap<>();     static     {         add( "smack fools", smackfools.class );         add( "have nap", naptime.class );     }      private static void add(string name, class<? extends activationeffect> behaviour) {         assert !map.containskey(name);         assert behaviour!=null && name!=null;         map.put(name, behaviour);     }      public static activationeffect build(string name)      {         activationeffect res;         try {             res = map.get(name).newinstance();         } catch (instantiationexception | illegalaccessexception ex) {             res = null;         }         if ( res==null )             throw new illegalargumentexception( "incorrect behaviour name : " + name );         return res;     } } 

when want add new effect need in static block.
new object of proper class name :

item.setactivationeffect(activationeffectsfactory.build(activationeffect)); 

Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -