Assume, I load the class by the ClassLoader
at the runtime:
Class<MyInterface> clazz = (Class<MyInterface>)getClass().getClassLoader().loadClass("ImplementerOfMyInterface");
The new instance I can create then by
MyInterface myInt = clazz.newInstance();
But when I need to get the instance of the singleton by its name that implements the MyInterface
instead of creating the new one, what should be done?
Instead of invoking newInstance
, you could invoke a static "getInstance" method (or whatever singleton getter method name you use).
For example:
public class ReflectTest {
public static void main(String[] args) throws Exception {
Class clazz = Class.forName("ReflectTest");
Method m = clazz.getDeclaredMethod("getInstance", null);
Object o = m.invoke(null, null);
System.out.println(o == INSTANCE);
}
public static ReflectTest getInstance() {
return INSTANCE;
}
private static final ReflectTest INSTANCE = new ReflectTest();
private ReflectTest() {
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.