I read this :Breaking of sinlgleton by two different class loaders But I can't create more than one instance of a Singleton with more than one class loader. Can some one help me provide an example of how you can break the Singleton pattern with multiple class loaders please?
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{
}
Aucun commentaire:
Enregistrer un commentaire