views:

1357

answers:

2

My Java is rusty so please bear with me. In C I can do:

int someFunc(void)
{
  printf("I'm in %s\n", __func__);
}

In Java, can I lexically get to the name or class of the type currently being defined. For example, if I have:

import org.apache.log4j.Logger;

class myClass {
    private static final Logger logger = Logger.getLogger(myClass.class);
...
}

It seems wrong to repeat "myClass" in the getLogger() argument. I want "getLogger(__CLASS__)" or "getLogger(this.class)" or something. (I know both of those are silly but they should point to what I'm looking for.) Does the Java compiler really not know what class it's in the middle of as it processes source?

+5  A: 

Unfortunately, there is no easier way if you are in a static context (as you are here). If the logger were an instance variable, you could use getClass(), but then you would have to worry about subclasses.

For this particular case, an alternative is to use log5j instead. log5j is a wrapper around log4j with convenience methods like getLogger(), which infers the correct class by walking up the stack. So your code would become:

import com.spinn3r.log5j.Logger;
class myClass {
    private static final Logger logger = Logger.getLogger();
    ...
}

And you can copy-and-paste the same declaration into all your classes without any problems.

Michael Myers
+5  A: 

I could not resist.

Here's the implementation of what mmyers refers but home made :)

Basically you throw an exception and get the 2nd element of the stack to get the class name.

I still think it is better to have it as instance member.

:)

package some.utility.packagename;   
import java.util.logging.Logger;

import some.other.packagename.MyClass;

public class LoggerFactory {
    public static Logger getLogger() {
        StackTraceElement [] s = new RuntimeException().getStackTrace();
        return Logger.getLogger( s[1].getClassName() );
    }
    public static void main (String [] args) {
        MyClass a = new MyClass();
    }
}

Usage:

package some.other.packagename;
import java.util.logging.Logger;

import static some.utility.packagename.LoggerFactory.getLogger;

public class MyClass {

    private static final Logger logger = getLogger();
    static{
         System.out.println(MyClass.logger.getName());
    }

}
OscarRyz
That looks just about like my own homemade logging wrapper. :)
Michael Myers