Image

Imagebanana wrote in Imagejava_dev 😊pleased

Class name in a static method (again)

If you've used any logging toolkit (Log4J, Apache LogKit, the one that ended up in JDK 1.4, the one I wrote (!), etc. etc.) you will quite probably have created loggers with the class name as a parameter to the constructor, something like this:


private static Logger log = new Logger ( "my.class.name" );
// or...
private static Logger log = new Logger ( ThisClass.class.getName() );

The problem is that you have to hard code the class name in one way or another. If (like me) you tend to copy that kind of code around, then sooner or later the logger will get initialised with the wrong class name.


I asked about this some time ago, and Imagerenniekins had a nice suggestion. However, it relies on JDK 1.4. Ever since I've used Java, work projects have been a version behind, so I can't use it.


Today I was looking at Cocoon logging API docs, and they have another solution that should work in any JDK.


Here's an example.
To see this working, save the following all as StaticNameTest.java, compile and run.
class StackProbe
    extends SecurityManager
{
  private static StackProbe instance = new StackProbe ();

  public static String getMyClassName ()
  {
    Class [] classes = instance.getClassContext ();
    String   result  = null;

    if ( classes.length > 1 )
    {
      result = classes [ 1 ].getName ();
    }

    return result;
  }
}

public class StaticNameTest
{
  private static String thisClass = StackProbe.getMyClassName ();

  public static void main ( String [] args )
  {
    System.out.println ( thisClass );
    new AnotherClass ().someMethod ();
  }
}

class AnotherClass
{
  private static String thisClass = StackProbe.getMyClassName ();

  public void someMethod ()
  {
    System.out.println ( thisClass );
  }
}

The output is spectacularly unspectacular, but the point is that the values of thisClass are not hard coded anywhere.


I found a nifty way of colouring the text with EditPlus. 8~)


TO DO: Put StackProbe into some suitable package and make it public.