我读到这个:两个不同的类加载器破坏单例但是我不能用一个以上的类加载器创建一个以上的单例实例。 有人可以帮我提供一个例子,说明如何使用多个类加载器打破单例模式吗?
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
ClassLoader cl1 = new CustomClassLoader();
ClassLoader cl2 = new CustomClassLoader();
Class<?> singClass1 = cl1.loadClass(SingletonObject.class.getName());
Class<?> singClass2 = cl2.loadClass(SingletonObject.class.getName());
Method getInstance1 = singClass1.getDeclaredMethod("getSingletonObject");
Method getInstance2 = singClass2.getDeclaredMethod("getSingletonObject");
Object singleton1 = getInstance1.invoke(null);
Object singleton2 = getInstance2.invoke(null);
System.out.println("ok");
}
}
public class SingletonObject {
private static SingletonObject ref;
private SingletonObject () //private constructor
{ }
public static SingletonObject getSingletonObject()
{
if (ref == null){
ref = new SingletonObject();
System.out.println("create new");
}else{
System.out.println("already have it");
}
return ref;
}
public Object clone() throws CloneNotSupportedException
{throw new CloneNotSupportedException ();
}
}
public class CustomClassLoader extends ClassLoader{
}