How to use Reflection to destroy Singleton Pattern.

Reflection can be used to destroy all the above singleton implementation approaches.  Let’s  see  this  with  an  example  class.

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class SingletonTest {

    @SuppressWarnings("rawtypes")
    public static void main(String[] args) {

        Singleton singleton = Singleton.getInstance();
        System.out.println(singleton.hashCode());

        try {
            Class correctSingClassObj = Class.forName("com.dp.Singleton");
            Constructor[] constructorArray = correctSingClassObj.getDeclaredConstructors();
            for (Constructor constructor : constructorArray) {
                constructor.setAccessible(true);
                Singleton s = (Singleton) constructor.newInstance();
                System.out.println(s.hashCode());
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

The output of the program is:

366712642
1829164700

  We notice that hashCode of both the instances are not same thus those are different instances that destroys the singleton pattern.

 

core java 12 Creational-Pattern 12

FOLLOW US ON LinkedIn



Explore Tutu'rself