jeudi 18 janvier 2018

Avoid multiple creation of a singleton using refletion

is there a way to avoid multiple new of a singleton class using reflection?

by wikipedia:

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object.

Example code:

public class Singleton {

    private static Singleton singleton;
    private int singletonId;

    private Singleton() {
        this.singletonId = new Random().nextInt(1000);
        System.out.println("creating new singleton: " + this.singletonId);
    }

    public static Singleton getInstance() {
        if(Singleton.singleton == null)
            return Singleton.singleton = new Singleton();
        else
            return Singleton.singleton;
    }

    @Override
    public String toString() {
        return "singleton ID: " + this.singletonId;
    }

}

Main class:

public class Main {

    public static void main(String [] args) {

        List<Singleton> list = new ArrayList<>();

        for(int i = 0; i < 5; i++) {
            Singleton singleton = Singleton.getInstance();
            list.add(singleton);
            System.out.println(i + ": " + singleton);

            try {
                Field field = singleton.getClass().getDeclaredField("singleton");
                field.setAccessible(true);
                field.set(singleton, null);
            } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
                e.printStackTrace();
            }   
        }

        System.out.println("lista: " + list);
    }
}

A solution could be to disable reflection. It's possible?

Aucun commentaire:

Enregistrer un commentaire