I have a class X which is extended by various classes. X needs to know each subtype that exists of it at runtime. So my idea was to create a static method "static init()" in X that takes a Class as parameter. The problem is that a subclass of X is required to be initialized via its static-init-blocks before the call to init() happens. X for example may discover some of the static fields of the subclass which may be of any declared type. So take this code for example:
class X {
X() {
/*This would be one idea but does not work
in this concrete example.*/
init(getClass());
}
static void init(Class<? extends X> c) {
if(c.getDeclaredField("a").get(null) == null) {
throw new AssertionError();
}
}
}
class Y extends X {
static X a = new X();
static {
/*Another idea. Works totally fine but
I dont want to trust subclasses that
they do that correctly.*/
init(Y.class);
}
}
So what I am looking for is a way to somehow get my init()-method called as the last step in the static initialization of a class. Or any other way to prevent the AssertionError from happening.
Edit: Because this lead to misunderstanding in the comments, I actually want to do the second thing. I want my method to be called within the static initialization of any class that subclasses my class (either directly or indirectly). I don't know which subclasses exist, I don't know anything about their structure and all assertions must be checked at runtime (via reflection). My class and the subclasses may not even be compiled by the same compiler on the same machine and/or by the same people.
Edit2: Maybe I can build a ClassLoader that is a simple proxy to the System-ClassLoader and replace the System-ClassLoader with it. If the loaded class is then a subclass of my class I can initialize it and call my method. Unfortunately I don't know much about ClassLoaders (yet) and there are not much tutorials or help on the net regarding this topic. So can anyone having experience with custom ClassLoaders tell me if this is possible? What happens if some other library in my classpath does also install a custom ClassLoader at any point in time?
Edit3: What I don't want to do - if there is any other option - is direct byte-code modifications.