[英]java: how to get singleton instance by classloader
假设我在运行时通过ClassLoader
加载了该类:
Class<MyInterface> clazz = (Class<MyInterface>)getClass().getClassLoader().loadClass("ImplementerOfMyInterface");
我可以通过以下方式创建新实例
MyInterface myInt = clazz.newInstance();
但是,当我需要通过实现MyInterface
名称来获取单例的实例而不是创建新实例时,该怎么办?
除了调用newInstance
,您可以调用静态的“ getInstance”方法(或使用的任何单例getter方法名称)。
例如:
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() {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.