Skip to main content
  1. My Blog posts/

Singleton !! … singleton ?? (the code)

·132 words·1 min·
medium
Víctor (Bit-Man) Rodríguez
Author
Víctor (Bit-Man) Rodríguez
Algorithm Junkie, Data Structures lover, Open Source enthusiast

Singleton !! … singleton ?? (the code) #

After my previous post on singletons I went for some Java sample to show the way it was created does not allow to create a singleton.

To play with it just checkout the code

svn checkout https://gitlab.com/bit-man/javalab.git javaLab

and run the JUnit test located at bitman.test.singleton.SingletonTest (it’s IntelliJ IDEA ready). In this class you’ll find the method testBadSingleton that creates two differents objects from MyFalseSingleton class. This can be done because there’s unless one public constructor, tested in the first line : assertEquals(1, Class.forName(“bitman.test.singleton.MyFalseSingleton”).getConstructors().length);

The testARealSingleton method uses the class MySingleton allow one object creation only (the singleton). As a bonus I was able to create another class from MySingleton but using reflection and setting the private constructor accesibility to “” through reflection.

Enjoy!