Given an object, how do we check if a class is Singleton or not?
Currently I am using this
public class SingletonClass implements IsSingleton
where IsSingleton
is a blank interface which I implement on singleton classes. So the class can be tested as singleton
SingletonClass obj = SingletonClass.getInstance();
if(obj instanceof IsSingleton)
System.out.println("Class is Singleton");
else
System.err.println("Class not singleton");
Is there a better way to determine a Singleton class. I have tried my way through reflection
but the problem there is getConstructors()
return only declared public classes. So it will treat a class without a declared constructor as Singleton.
Singleton is a semantic definition, one this is not generally testable thru code. No interface or any other scheme can guarantee that the class operates solely as a singleton.
Because of this (semantic nature) it would be better IMO to create a custom annotation to indicate this feature
I think this may help you.... Whenever any object is created in the memory, there is always a hashcode associated with it. This hashcode is calculated by a mathematical operation using few parameters, such as starting memory allocation address.So, if you will call hashcode() on any object any number of times, it's going to return the same hashcode. So, simply call the method which is returning your expected singleton type of object and call hashcode() method on it. If it prints the same hashcode each time, it means it's singleton, else it's not.
Lot of people are saying that instanceof keyword can help decide you whether an object is singleton ot not. But, I really don't understand how is this possible? instanceof just lets us examine whether the instance is of any particular class . So, if there are multiple instances of class A and they are not created by singleton pattern, then checking instanceof for any of them is always going to return true. But, it can't be called as singleton because, separate instance exists for each object in the memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With