简体   繁体   English

java:如何通过类加载器获取单例实例

[英]java: how to get singleton instance by classloader

Assume, I load the class by the ClassLoader at the runtime: 假设我在运行时通过ClassLoader加载了该类:

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? 但是,当我需要通过实现MyInterface名称来获取单例的实例而不是创建新实例时,该怎么办?

Instead of invoking newInstance , you could invoke a static "getInstance" method (or whatever singleton getter method name you use). 除了调用newInstance ,您可以调用静态的“ getInstance”方法(或使用的任何单例getter方法名称)。

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() {
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM