问题
I have an abstract class Parent, with 2 subclasses A and B. Parent has one static method called do(). I am wondering if there is a way for that static method to add log info in Logger for class A when it's called as A.do() and log B when it's called as B.do(). The usual
protected final Logger LOGGER = Logger.getLogger(getClass());
won't work as do() is a static method so Logger needs to be static as well, but the getClass() method is obviously not static.
Thanks.
回答1:
I wouldn't recommend it, but if you really want it...
public class A {
public static void do() {
doImpl(A.class);
}
protected static void doImpl(Class<?> refClass) {
}
}
public class B extends A {
public static void do() {
doImpl(B.class);
}
}
回答2:
private final static Logger LOGGER = Logger.getLogger(A.class);
Every class having its own logger: specifying the class is fine.
回答3:
Best practice is to declare LOGGER static, e.g.
protected final static Logger LOGGER = Logger.getLogger(getClass());
This way you can use LOGGER from dynamic and static methods.
Also each class should have its own instance of the logger. So I would change protected to private.
ALSO, instead of calling "getClass()" you should call "MyApp.class", e.g.
private final static Logger LOGGER = Logger.getLogger(MyApp.class);
来源:https://stackoverflow.com/questions/15571950/logging-static-methods-in-a-parent-class