An alternative is to return the instance from the static init method and use all methods of the returned instance.
MyInstance instance = MyLibrary.init(context, and, whatever, else); instance.doSomethingThatRequiresContext();
Now the call order cannot be canceled.
Then, all you need to protect is calling init twice. What you could do with either an exception at runtime or return the previous instance, I personally would run Runtime if init is called twice.
I want only one instance of my classes to exist and can be captured anywhere in the code without passing references.
Specify getInstance , which is valid only after calling init
//MyLibrary.getInstance() would throw before init MyInstance instance1 = MyLibrary.init(context, and, whatever, else); MyInstance instance2 = MyLibrary.getInstance(); assertSame(instance1, instance2);
Please note that although it differs only in the subtlety of your original, separating the responsibilities of distributing and managing singleton to MyLibrary , at least only the init and getInstance should verify that init was called or not, None of the MyInstance methods should bother.
Even if I use exceptions at runtime, it would be dangerous to use.
I do not think that you cannot solve this problem without them. It is more dangerous to quit when something is seriously wrong, as the user did not initialize. Just add a good error message to back up the documentation.
Full list:
public final class MyInstance { private final Context context; MyInstance(Context context, and, whatever, else) {