Suppose you have a Singleton A whose getInstance() throws some Exceptions.
Further suppose that A is used everywhere throughout the program and while A.getInstance().doSomethingUseful() is fine, a lot of code inherits from Constants interface and i’d like to declare:
A a = A.getInstance() in Constants, allowing everyone tho implements Constants access to a.
As expected, though, Java complains that method throws Exceptions and as such can’t be declared in an interface.
Is there a workaround around it?
I think this is really not a good idea. You’re attempting to tie the lifecycle of that object directly into the structure of the classes implementing that interface.
If you have to use a singleton, then better to reference it explicitly via the
getInstance()method. It’s relatively intuitive. Make your instantiation exceptions runtime if you have to.Better still is to accept the premise that the singleton pattern is regarded as an anti-pattern and consider alternatives such as injection-of-control.