gpt4 book ai didi

java - 枚举 Logger 中的 NullpointerException

转载 作者:行者123 更新时间:2023-12-02 11:33:03 25 4
gpt4 key购买 nike

我有一个 ValueRepository 类,并且想在其中使用记录器。以下代码始终抛出 NullPointerException。

public enum ValueRepository {

INSTANCE;

private static final Logger LOGGER = LoggerFactory.getLogger(ValueRepository.class.getName());

private Map<String, Set<String>> key2value;
private Map value2key;

ValueRepository() {

key2value = new HashMap();
value2key = new HashMap();

load("keyValue.txt");
}

public int size() {
return key2value.size();
}

public boolean hasKey(String key) {
return key2value.containsKey(key);
}

public boolean hasValue(String value) {
return value2key.containsKey(value);
}

public Set<String> getValues(String key) {
return key2value.get(key);
}

public String getKey(String value) {
return (String) value2key.get(value);
}

private void load(String filePath) {

BufferedReader br;
try {
br = IOUtils.fileReaderAsResource(filePath);
String line = null;
while ((line = br.readLine()) != null) {
LOGGER.info("test");
line = line.trim();
}
br.close();
} catch (IOException io) {
LOGGER.error("Can't load the file: " + filePath);
io.printStackTrace();
}
}

public static void main(String[] args) {

// do nothing
}

这不应该起作用吗?

这个问题与链接有很大不同。它特别是关于为什么它在枚举中的记录器中不起作用。

编辑:

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/Users/congmi/.m2/repository/org/apache/logging/log4j/log4j-slf4j-impl/2.6.2/log4j-slf4j-impl-2.6.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/congmi/.m2/repository/org/slf4j/slf4j-log4j12/1.7.21/slf4j-log4j12-1.7.21.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory]
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
at com.qe.repository.ValueRepository.load(ValueRepository.java:56)
at com.qe.repository.ValueRepository.<init>(ValueRepository.java:26)
at com.qe.repository.ValueRepository.<clinit>(ValueRepository.java:14)

Process finished with exit code 1

最佳答案

因为您将 ValueRepository 单例设计为 enum你得到了静态常量的初始化序列:

  1. INSTANCE(隐式调用构造函数)
  2. 记录器

您需要将此初始化顺序更改为:

  1. 记录器
  2. 实例

您无法使用 enum 到达此序列,因为 Java 语法坚持enum 实例是第一个。

这意味着,您需要将单例实现为普通的,而不是枚举

public class ValueRepository {

private static final Logger LOGGER = LoggerFactory.getLogger(ValueRepository.class.getName());

public static final ValueRepository INSTANCE = new ValueRepository();

// remaining code unchanged

}

关于java - 枚举 Logger 中的 NullpointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49141972/

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