How to find if a class is a singleton class from the object?

java, singleton

Solution

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

Problem

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.

Original source