If you know all the classes @ runtime, and can load all of those classes using the class loader that loaded the executing class, You can simply store the classes in a data structure by referencing the Class object via the "class" property. You simplify the exception handling a bit, and the class is guaranteed to be initialized properly, while loading via a class loader does not. I've always been taught to instantiate classes via Class.forName() or the class property only using class loaders explicitly if I need to load a class not available to the current class loader.
This example uses generics so it requires at least a Java 5 environment
package webwhy;
import java.util.HashMap;
import java.util.Map;
public class Test implements Printer {
private String member = "test 1 class";
public Test() {}
public Test(String member) {
this.member = member;
}
public void print() {
System.out.println(member);
}
public static void main(String[] args) {
Map<String, Class<? extends Printer>> classes = new HashMap<String, Class<? extends Printer>>(2);
classes.put("Test App", Test.class);
classes.put("Test 2 App", Test2.class);
try {
classes.get("Test App").newInstance().print();
classes.get("Test 2 App").newInstance().print();
}
catch(InstantiationException e) {
e.printStackTrace();
}
catch(IllegalAccessException e) {
e.printStackTrace();
}
}
}
class Test2 extends Test {
public Test2() {
super("test 2 class");
}
}
interface Printer {
void print();
}