You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

log4j中NOPLogger类构造函数使用未声明实例变量问题咨询

Why can NOPLogger assign repository/level/parent without declaring them?

Great question! Let's unpack this log4j detail step by step:

  • First, remember that NOPLogger extends the Logger class. Those three variables (repository, level, parent) aren't missing—they're defined directly in the parent Logger class.
  • In Java, subclasses inherit all non-private instance variables from their parent class. Log4j's base Logger class declares these variables with at least protected access (or package-private, if they share the same package), which lets subclasses like NOPLogger access and modify them directly using the this keyword.

To put it in context, the parent Logger class likely has something like this under the hood:

public class Logger {
    protected LoggerRepository repository;
    protected Level level;
    protected Logger parent;
    
    // Constructor, methods, and other core logic...
}
  • This design makes perfect sense for log4j's architecture: all logger subclasses share the same core state (like logging level, parent logger, and repository) defined in the base Logger, so there's no need to re-declare these fields in every subclass. It keeps the code DRY (Don't Repeat Yourself) and maintains consistency across the logger hierarchy.
  • When NOPLogger sets this.repository = repo and the others, it's simply initializing the inherited fields from its parent class, not creating new ones in the subclass.

内容的提问来源于stack exchange,提问作者Squeez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:22:18