Skip to content

Instantly share code, notes, and snippets.

@kevalpatel2106
Created November 29, 2016 09:53
Show Gist options
  • Save kevalpatel2106/6d2213e7703bbfcb953882cf29bcdfc7 to your computer and use it in GitHub Desktop.
Save kevalpatel2106/6d2213e7703bbfcb953882cf29bcdfc7 to your computer and use it in GitHub Desktop.
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());
}
}
@optimusgoal
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment