I at one time used class forname newinstance but newinstance is deprecated. I wanted to be able to pass a class name as a string and be able to load a class, so I came up with:
public static Object getClass(String myclass) throws ClassNotFoundException,
NoSuchMethodException,
InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException {
Class clz = Class.forName(myclass);
return clz.getDeclaredConstructor().newInstance();
}
Which works good. And usage is:
Jim.Newpager apager = (Jim.Newpager) Jim.Jiminject.getInstance().getClass("Jim.Newpager");
Does that look alright?
The whole class that does the inject is:
package Jim;
import java.lang.reflect.InvocationTargetException;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
public class Jiminject {
private static final Jiminject instance
= new Jiminject();
private Jiminject() {
}
public static Jiminject getInstance() {
return instance;
}
public static Object getClass(String myclass) throws ClassNotFoundException,
NoSuchMethodException,
InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException {
Class clz = Class.forName(myclass);
return clz.getDeclaredConstructor().newInstance();
}
}
I use for Tomcat, all works good.
Class.forName("Jim.Newpager").newInstance();
directly? Your class doesn’t even make usage easier — on the contrary. \$\endgroup\$getConstructor().newInstance()
instead of abbreviating. I still don’t see the point of wrapping this straightforward logic into a singleton whose verbose usage doesn’t make the calling code any more concise. \$\endgroup\$