Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.06 KB | None | 0 0
  1. import java.lang.reflect.Constructor;
  2.  
  3. // Singleton class
  4. class Singleton {
  5.     // public instance initialized when loading the class
  6.     public static Singleton instance = new Singleton();
  7.    
  8.     private Singleton()  {
  9.         // private constructor
  10.     }
  11. }
  12.  
  13. public class GFG {
  14.     public static void main(String[] args) {
  15.         Singleton instance1 = Singleton.instance;
  16.         Singleton instance2 = null;
  17.         try {
  18.             Constructor[] constructors = Singleton.class.getDeclaredConstructors();
  19.             for (Constructor constructor : constructors) {
  20.                 // Below code will destroy the singleton pattern
  21.                 constructor.setAccessible(true);
  22.                 instance2 = (Singleton) constructor.newInstance();
  23.                 break;
  24.             }
  25.         } catch (Exception e) {
  26.             e.printStackTrace();
  27.         }
  28.        
  29.     System.out.println("instance1.hashCode():- " + instance1.hashCode());
  30.     System.out.println("instance2.hashCode():- " + instance2.hashCode());
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement