I have
public class A {
static X s_x = new X(A.class);
}
and
public class B {
static X s_x = new X(B.class);
}
and so on for many classes without any special relationship or commonality. What I really wish I could do is have s_x initialized in a superclass, but with descendant-class-specific code; this is impossible since static code is not overridable. So, I want to at least make my copy-paste easier. I want a magic expression which evaluates to the Class object, i.e. to write:
static X s_x = new X(/* magic expression here */);
where the magic expression is the same regardless of the class in which I declare my X in, but does the same as the examples above. Second-best option would be a static method to the same effect.
Notes:
- Java 6 if possible.
- This question is not (necessarily) about logging…
Some of the answers here have the idea for a solution, but not quite the code snippet I need. So here it is, working on any JVM:
or, for selected JVMs, as per Peter Lawrey’s suggestion: