Created
November 29, 2016 09:53
-
-
Save kevalpatel2106/6d2213e7703bbfcb953882cf29bcdfc7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SingletonTester { | |
public static void main(String[] args) { | |
//Create the 1st instance | |
SingletonClass instance1 = SingletonClass.getInstance(); | |
//Create 2nd instance using Java Reflection API. | |
SingletonClass instance2 = null; | |
try { | |
Class<SingletonClass> clazz = SingletonClass.class; | |
Constructor<SingletonClass> cons = clazz.getDeclaredConstructor(); | |
cons.setAccessible(true); | |
instance2 = cons.newInstance(); | |
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) { | |
e.printStackTrace(); | |
} | |
//now lets check the hash key. | |
System.out.println("Instance 1 hash:" + instance1.hashCode()); | |
System.out.println("Instance 2 hash:" + instance2.hashCode()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This still is not fullproof as to What would happen if I create an instance of SingleTonClass first using reflection and then using getInstance.
This class allows me to create two instances in that case