If I have 2 classes, \"A\" and \"B\", how can I create a generic factory so I will only need to pass the class name as a string to receive an instance?
Example:
Class c= Class.forName(className);
return c.newInstance();//assuming you aren't worried about constructor .
For invoking constructor with argument
public static Object createObject(Constructor constructor,
Object[] arguments) {
System.out.println("Constructor: " + constructor.toString());
Object object = null;
try {
object = constructor.newInstance(arguments);
System.out.println("Object: " + object.toString());
return object;
} catch (InstantiationException e) {
//handle it
} catch (IllegalAccessException e) {
//handle it
} catch (IllegalArgumentException e) {
//handle it
} catch (InvocationTargetException e) {
//handle it
}
return object;
}
}
have a look