Let's say I have a lot of similar classes (Units in a RTS in this example),
that is, the class Unit
, and the subclasses UnitA
,UnitB
,UnitC
etc.
All Unit classes have the following constructor (including Unit)
public class UnitX {
public UnitX(FileReader fr) {
...read parameters for constructing the unit...
}
}
My file containing the parameters have the form
UnitX params
UnitY params
....
and creating a list of all units in a file would be a while-loop like
Class[] params = {FileReader.class};
while(fr has more to read) {
String unitType = fr.getString();
Unit u = (Unit)
java.lang.reflect.Constructor constr = Class.forName(unitType).getConstructor(params);
Unit u = (Unit)constr.newInstance(new Object[]{fr});
list.add(u);
}
I realized that I use this pattern very often when I create objects from files. My question is, is this a bad pattern? Is there a better way to do this?