How do I get the Class object in a static method without using the class name?

advertisements

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...

I also had this strange requirement once and I tried to search but did not find anything, so I guess the answer is it's not possible may be.

But I was told to rethink my approach and when I tried I figure out the same solution without this strange requirement. So please rethink your approach. I'm sure you'll be able to solve it like me. Also, if you can post the problem/scenario you are trying to solve,may be I can help.