So I have two projects A and B, and project B is imported in project A, and in project B I want to initialize some objects which have static initializers.
The problem is, they aren't getting called (already tested with final
keyword, does not help).
So I actually want to have a small system and it should go this way (every class decribed here are in project B):
- class A is a main class in which you can call a method
addClassToLoad()
* to add other classes (which will be "loaded" when methodstart()
in class A will be called); - classes B, C and D call method
addClassToLoad()
from its static initializer; - when some class from project A calls a method
start()
, class A lists all classes it has gotten and calls a methodonLoad()
(explained in *).
And every method is static, so it's meant to be only one (no "instancing").
Saddly, static initializers aren't getting called.
And the question is: do I do something wrong (or maybe it is not possible at all) or maybe there is another way to do this small system? (I just don't really want to write in class A about every class, which must be loaded at start()
method)
*addClassToLoad()
takes an interface which has one method onLoad()
, so it is getting called when method start()
is called in class A
In code version:
class A:
public class A {
private static ArrayList<ClassToLoad> classesToLoad;
public static void addClassToLoad(ClassToLoad c) {
if (classesToLoad == null)
classesToLoad = new ArrayList<ClassToLoad>();
classesToLoad.add(c);
}
public static void start() {
for (ClassToLoad c : classesToLoad) {
c.onLoad();
}
}
}
class B (and others (C, D etc.) like this one):
public class B {
static {
A.addClassToLoad(new ClassToLoad() {
public void onLoad() {
load();
}
});
}
private static void load() {
// do something here on load ...
}
}
class ClassToLoad:
public interface ClassToLoad {
public void onLoad();
}