jeudi 27 avril 2017

Prevent Cracking Singleton using reflection

I came across the below example where a singleton class can be instantiated using reflections. The code is like below

public class SingletonExploitationExample {

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        MySingleTon.getInstance();
        Constructor<MySingleTon> constructor = MySingleTon.class.getDeclaredConstructor();
        constructor.setAccessible(true);
        MySingleTon obj1 = constructor.newInstance();
        MySingleTon obj2 = constructor.newInstance();
        MySingleTon obj3 = constructor.newInstance();
        obj1.printN();
    }
}

final class MySingleTon {
    private static MySingleTon instance = null;

    private static int count = 0;
    private MySingleTon(){
        count++;
    }

    public void printN(){
        System.out.println(count);
    }

    public static MySingleTon getInstance(){
        if(instance == null){
            synchronized (MySingleTon.class){
                if(instance == null){
                    instance = new MySingleTon();
                }

            }
        }
        return instance;
    }
}

Is there any way this can be avoided or a singleton be made to have only one instance(with reflection also user should not be able to instantiate a new object) ?

Aucun commentaire:

Enregistrer un commentaire