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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With