我已经到处检查了这个问题的解决方案,尽管它看起来很简单,但根本找不到。
打电话给myFunction()
时,我一直得到NullPointerException
:
private static Map<String, Map<String, Integer>> data;
public Class() {
data = new Map<String, Map<String, Integer>();
}
public static void myFunction(String key, String val0, int val1) {
boolean createNewEntry = false;
if(null == data) {
createNewEntry = true;
}
else if(!data.containsKey(key)) {
createNewEntry = true;
}
if(createNewEntry) {
data.put(key, new HashMap<String, Integer>()); // This throws a NullPointerException.
}
data.get(key).put(val0, data.get(key).get(val0) + val1);
}
堆栈跟踪(删除了一些特定于项目的数据(如下所示:
Could not pass [Event] to [JAR file] v1.0.0
org.[parent].event.EventException
... (irrelevant)
Caused by: java.lang.NullPointerException
at net.[package name].[class].myFunction([source file].java:93)
at net.[package name].[class].otherFunction([source file].java(108)
at net.[package name].[other class].anotherFunction([other file].java(65)
at net.[package name].[main class].on[Event]([main file].java:97) ~[?:?]
at sun.reflect.GeneratedMethodAccessor2.invoke(Unknown Source) ~[?:?]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:[versioning number]]
at java.lang.reflect.Method.invoke(Unknown Source) ~[?:[versioning number]]
at org.[a different package name].plugin.java.JavaPluginLoader$1.execute([a file].java:301) ~[[versioning number]:[more data]]
... 15 more
提前感谢您对此问题的任何见解。
你应该使用static
块来初始化静态变量:
public class yourClass {
private static Map<String, Map<String, Integer>> data;
static {
data = new Map<String, Map<String, Integer>();
}
public static void myFunction(String key, String val0, int val1) {
// ...
}
}
当您在构造函数中初始化映射时,这无济于事,因为您从不调用构造函数。