There are a number of cases when you may not know exactly what class you will be instantiating and want to be able to dynamically instatiate specific classes based on a configuration file or a condition during runtime.
To do so, you will need to define an Interface for your classes and can then use the following code as a guide:
String className = args[0];
String qualifiedClassName = null;
Class instanceClass = null;
try {
qualifiedClassName = fClassPackage.getName() + “.” + className;
instanceClass = Class.forName(qualifiedClassName);
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
Interface dynamicInstance = null;
try {
dynamicInstance = (Interface) instanceClass.newInstance();
} catch(InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
// Set fields in new instance
dynamicInstance.setSomething(“foo”);
Keep in mind that dynamically instantiated classes must include a no argument constructor. As a result, you will need to have mutator methods for each field that requires configuration in your class.