You could use the full class name as in package.ClassName, reflection, and Class.forName(theName).
For instance with a String object:
try {
String newString = (String)Class.forName("java.lang.String").newInstance();
}
catch (IllegalAccessException iae) {
// TODO handle
}
catch (InstantiationException ie) {
// TODO handle
}
catch (ClassNotFoundException cnfe) {
// TODO handle
}
So your method could roughly look like:
@SuppressWarnings("unchecked")
public static <T> T getInstance(String clazz) {
// TODO check for clazz null
try {
return (T)Class.forName(clazz).getMethod("getInstance", (Class<?>[])null).invoke(null, (Object[])null);
}
catch (ClassNotFoundException cnfe) {
// TODO handle
return null;
}
catch (NoSuchMethodException nsme) {
// TODO handle
return null;
}
catch (InvocationTargetException ite) {
// TODO handle
return null;
}
catch (IllegalAccessException iae) {
// TODO handle
return null;
}
}
Edit for OP:
The (Class<?>[])null and (Object[])null are null arguments cast as their expected type.
Basically:
- the
getMethod method of Class takes a String representing the method's name, and a varargs of Class<?> representing its parameter types. The method we call (getInstance) takes no arguments, therefore the argument to getMethod is null, but we want to cast it as the expected argument. More info here.
- the
invoke method of Method takes an Object as the target instance to invoke the method against (in our case, null since it's a class method) and a varargs of Object as the arguments. But again, your getInstance method takes no arguments, so we use null and cast it as an array of Object. More info here.