由两个不同的类装载机打破sinlgleton

Tun*_*fhf 4 java design-patterns

我正在设计下面的单身人士课程,我知道我的单身人士可以被打破

public class SingletonObject {
    private static SingletonObject ref;
    private SingletonObject () //private constructor
    { }

    public  static synchronized   SingletonObject getSingletonObject()
    {
        if (ref == null)
            ref = new SingletonObject();
                return ref;
        }


    public Object clone() throws CloneNotSupportedException
    {throw new CloneNotSupportedException ();
    }   
}
Run Code Online (Sandbox Code Playgroud)

下面的url已经建议单例可以用其他方法破解单例,但是我的查询是这个url中建议单例可以被类加载器破坏,同样的类可以由两个不同的类加载器加载,因此,你可以通过在由两个不同类加载器加载的类中调用其getInstance()方法来创建单例类的两个实例.这种方法可以工作,而不必诉诸于违反私人构造函数.

ClassLoader cl1 = new URLClassLoader(new URL[]{"singleton.jar"}, null);
ClassLoader cl2 = new URLClassLoader(new URL[]{"singleton.jar"}, null);
Class<?> singClass1 = cl1.loadClass("hacking.Singleton");
Class<?> singClass2 = cl2.loadClass("hacking.Singleton");
//...
Method getInstance1 = singClass1.getDeclaredMethod("getInstance", ...);
Method getInstance2 = singClass2.getDeclaredMethod("getInstance", ...);
//...
Object singleton1 = getInstance1.invoke(null);
Object singleton2 = getInstance2.invoke(null);
Run Code Online (Sandbox Code Playgroud)

请告知应采取什么措施来避免这种情况.

bsi*_*nau 5

如果要创建真正的单例,则应避免使用自定义类加载器 - 所有单例都应由公共父类加载器加载.

从问题中解决您的问题的示例,链接如下:

private static Class getClass(String classname) throws ClassNotFoundException {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    if(classLoader == null) 
        classLoader = Singleton.class.getClassLoader();
    return (classLoader.loadClass(classname));
}
Run Code Online (Sandbox Code Playgroud)

类似的问题: