I'm working with an abstract class and a (growing) set of subclasses of this class. For certain reasons all subclasses of A should implement the singleton pattern. During startup of the application there exists a List<Class<? extends A>>
and I would like to initialize all singleton-instances.
From what I see, my option here is to go for Reflection, enforcing by guidelines that all A-implementing classes have to have a defined constructor and invoke that via o.getDeclaredConstructor().newInstance();
.
I've also tried a different approach where I used overloading of static methods. That is, A defined a static initialize
method and all subclasses had to reimplement that method. The call can again be invoked via reflection.
The first approaches has the obvious disadvantage that violations of the programming-guideline result only in runtime-errors, not in compile-time errors. The second is even worse, if a subclass does not implement the static method, only the method in A
is called with no apparent exception thrown.
So: How do I enforce a uniform way to initialize in a set of singleton classes?
Edit:
A configuration-class generates a list of all children of A
during startup, those classes can be either registered directly in the configuration class programmatically or configured via a configurationfile:
private void initModules() {
Configurator.addModule("modulename", SubOfA.class);
...
}
private void initModuleFile() {
...
String name = in.readLine();
String classname = ...;
String modulename = ...;
Configurator.addModule(modulename, Class.forName(classname));
}