I have a situation where a subclass (let's call it SubClass
), during class initialization, calls a static method of the base class (let's call it BaseClass
) and passes SubClass.class
as a parameter to identify the specific class being initialized, or in Java:
public class SubClass extends BaseClass {
static { BaseClass.init(SubClass.class); }
...
}
Instead of BaseClass
having the method:
protected static void init(Class<?> c) {
...
}
what I would like to do is have BaseClass
call init
automatically, such as:
public class BaseClass {
static { init(thisclass); }
...
}
So, the question is, does Java have some keyword, represented by thisclass
above, that returns the class being initialized in a class initializer?
No, there isn't.
Also, as user2357112 said in the comments, the static initializer for BaseClass
is only going to run once, while initializing BaseClass
. It isn't like an instance constructor, run every time an instance of a subclass is created. Basically you should stick to your existing scheme.
It's also worth noting that if you're expecting subclasses to sort of "register themselves" with something, you may be surprised at when subclass initialization doesn't occur.
For example, if you have a static method foo
in the base class, then calling Subclass.foo()
won't initialize Subclass
- only the base class, because the subclass doesn't need to be initialized, as none of its code is executing.
See more on this question at Stackoverflow