duanjfeng
duanjfeng

Reputation: 98

Does class initialziation check its member method?

AS the class Log4jImpl below, I want to know whether its' initialization (class initialization not object), will cause org.apache.log4j.Level and org.apache.log4j.Logger to be initializaton?


import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class Log4jImpl{

  private static final String FQCN = Log4jImpl.class.getName();

  private Logger log;

  public Log4jImpl(String clazz) {
    log = Logger.getLogger(clazz);
  }

  public boolean isDebugEnabled() {
    return log.isDebugEnabled();
  }

  public boolean isTraceEnabled() {
    return log.isTraceEnabled();
  }

  public void error(String s, Throwable e) {
    log.log(FQCN, Level.ERROR, s, e);
  }

  public void error(String s) {
    log.log(FQCN, Level.ERROR, s, null);
  }

  public void debug(String s) {
    log.log(FQCN, Level.DEBUG, s, null);
  }

  public void trace(String s) {
    log.log(FQCN, Level.TRACE, s, null);
  }

  public void warn(String s) {
    log.log(FQCN, Level.WARN, s, null);
  }

}

Upvotes: 1

Views: 89

Answers (2)

dcernahoschi
dcernahoschi

Reputation: 15230

Intialization of class Logger will happen when its static getLogger method is invoked: in the constructor of Log4jImpl. The initialization of Level class will happen when one of its static fields are invoked: Level.ERROR, Level.DEBUG...

See when class initialization occurs in the Java language specs.

interface I {
    public static final int i = 1, ii = Test10.out("ii", 2), kk = Test10.out("kk", 3);
}
interface J extends I {
    int j = Test10.out("j", 3), jj = Test10.out("jj", 4);
}
interface K extends J {
    int k = Test10.out("k", 5);
}
class Test10 {
    public static void main(String[] args) {
        System.out.println(J.ii);
        System.out.println(K.j);
    }
    static int out(String s, int i) {
        System.out.println(s + "=" + i);
        return i;
    }
}

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533482

Using Log4jImpl.class will not load any additional classes. They will get loaded when you use them in the constructor.

BTW Normally XxxxImpl means you have an implementation of an interface Xxxx

Upvotes: 1

Related Questions