问题描述
我有以下类
public class MyClass { private static final Logger logger = Logger.getLogger(MyClass.class); static { logger.info("some text"); } }
可以肯定地假设,当我们到达logger.info时,log4j系统已初始化并准备发射日志?
看来,如果我能够做Logger.getLogger()并恢复有效的Logger实例,则意味着Log4j是初始化的,对呢?
推荐答案
是的,是.静态初始化器(即static {}块和静态变量的初始分配)都是按声明的顺序执行的.
log4j的默认初始化依赖于log4j class LogManager中的静态块,该LogManager一旦加载了Logger类,并且在首次使用之前加载了log4j class LogManager.这就是为什么您的建筑工作.
其他推荐答案
请参阅 JLS .它讨论了当您初次上课时会发生什么. 这个部分初始评估者.在回答您的问题时,AFAIK按照其发生的顺序执行静态块.加载类时将执行它们,当您创建其实例或访问其静态var/方法时,可能会发生.
问题描述
I have the following class
public class MyClass { private static final Logger logger = Logger.getLogger(MyClass.class); static { logger.info("some text"); } }
Is it safe to assume that by the time we reach logger.info, the log4j system is initialized and is ready to emit logs?
It seems that if I am able to do a Logger.getLogger() and get back a valid Logger instance, it means that Log4j is initialized, right?
推荐答案
Yes, it is. Static initializers (that is, both static {} blocks and initial assignments to static variables) are executed in the order they are declared.
Default initialization of log4j relies on a static block in a log4j class LogManager that is executed once Logger class is loaded, and it is loaded prior to its first use. This is why your construction works.
其他推荐答案
See this part of the JLS. It talks about what happens when you initialise a class. This part talks about static initialisers. In answer to your question then AFAIK the static blocks are executed in the order they occur. They will be executed when the class is loaded which can happen when you create an instance of it or access a static var/method of it.