gpt4 book ai didi

java - Logger.getLogger(class_name.class.getName()) 导致 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 07:12:06 26 4
gpt4 key购买 nike

问题是 Logger 没有使用 Logger.getLogger(class_name.class.getName()) 方法初始化。您可以看到下面的代码。我标记了导致异常的行。我必须注意,我也尝试过不使用静态 setLevel block 。

// File that contains logger
public class Experience {

private final static Experience INSTANCE = new Experience();
private final static Logger LOGGER = Logger.getLogger(Experience.class.getName());

private MainFrame main_frame;

static {
LOGGER.setLevel(Level.SEVERE);
}

public static Experience getInstance()
{
return INSTANCE;
}

private Experience()
{
try
{
FileHandler fh = new FileHandler(System.getProperty("user.dir") + "/log.txt");
fh.setFormatter(new XPLogFormatter());
LOGGER.addHandler(fh); // NULLPOINTEREXCEPION HERE
}
catch (Exception e)
{
e.printStackTrace();
}
}
}


// Just a loader
public class Loader
{
public static void main(String args[])
{
JFrame.setDefaultLookAndFeelDecorated(true);

SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
MainFrame main_frame = new MainFrame();
}
});
}
}


// Stripped down version of main frame
public class MainFrame extends JFrame
{
private Experience XP;

public MainFrame()
{
super();
XP = Experience.getInstance(this);
}
}


// Modified formatter
public class XPLogFormatter extends Formatter
{
@Override
public String format(LogRecord record)
{
StringBuffer buf = new StringBuffer(1000);
buf.append(formatMessage(record));
return buf.toString();
}
}

您能告诉我到底是什么导致了这个错误吗?

最佳答案

问题在于这两个静态变量初始值设定项是按文本顺序执行的:

private final static Experience INSTANCE = new Experience(); 
public final static Logger LOGGER = Logger.getLogger(Experience.class.getName());

因此,当第一行调用构造函数时,其中包括:

LOGGER.addHandler(fh);

...LOGGER 仍然为空。

最简单的修复方法就是颠倒声明的顺序...但另一个更清晰的替代方案是在静态初始化程序中完成所有操作:

private final static Experience INSTANCE;
public final static Logger LOGGER;

static {
LOGGER = Logger.getLogger(Experience.class.getName());
LOGGER.setLevel(Level.SEVERE);
INSTANCE = new Experience();
}

(出于兴趣,您真的希望记录器公开吗?)

关于java - Logger.getLogger(class_name.class.getName()) 导致 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12222424/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com