hou*_*aft 6 java nullpointerexception discord-jda
我正在开发 JDA Discord 机器人,每次运行它时,我都会遇到此异常。
java.lang.NullPointerException: Cannot read the array length because "<local3>" is null
at com.houseofkraft.handler.CommandHandler.scanIndex(CommandHandler.java:42)
at com.houseofkraft.core.DiscordBot.<init>(DiscordBot.java:68)
at com.houseofkraft.Stratos.main(Stratos.java:13)
Run Code Online (Sandbox Code Playgroud)
我试图制作一个基本的命令处理程序,这是它的代码:
public void scanIndex(Index index) throws IOException, InvalidLevelException {
String[] commandList = index.indexClass;
for (String classPath : commandList) {
if (classPath.startsWith("com.houseofkraft")) {
String[] classPathSplit = classPath.split("\\.");
String commandName = classPathSplit[classPathSplit.length-1].toLowerCase();
commandPaths.put(commandName, classPath);
DiscordBot.logger.log("Added " + commandName + " / " + classPath + " to path.", Logger.DEBUG);
}
}
}
Run Code Online (Sandbox Code Playgroud)
索引.java:
package com.houseofkraft.command;
public class Index {
public String[] indexClass;
public String[] getIndexClass() {
return indexClass;
}
public Index() {
String[] indexClass = {
"com.houseofkraft.command.Ping",
"com.houseofkraft.command.Test"
};
}
}
Run Code Online (Sandbox Code Playgroud)
我不太清楚为什么它会导致异常。谢谢!
编辑:这是我的 DiscordBot 代码
public DiscordBot() throws IOException, ParseException, LoginException, InvalidLevelException {
try {
if ((boolean) config.get("writeLogToFile")) {
logger = new Logger(config.get("logFilePath").toString());
} else {
logger = new Logger();
}
logger.debug = debug;
info("Stratos V1");
info("Copyright (c) 2021 houseofkraft");
info("Indexing commands...");
// Add the Commands from the Index
commandHandler.scanIndex(new Index()); // here is the part that I call
info("Done.");
info("Connecting to Discord Instance...");
jda = JDABuilder.createDefault(config.get("token").toString()).addEventListeners(new EventHandler(commandHandler)).build();
if (jda != null) {
info("Connection Successful!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 2
public String[] indexClass你的类中有一个成员变量Index。在你的构造函数中,你创建一个新变量
String[] indexClass = {
"com.houseofkraft.command.Ping",
"com.houseofkraft.command.Test"
};
Run Code Online (Sandbox Code Playgroud)
这样你的成员变量就保持未初始化状态。将构造函数中的代码更改为
this.indexClass = {
"com.houseofkraft.command.Ping",
"com.houseofkraft.command.Test"
};
Run Code Online (Sandbox Code Playgroud)
顺便说一句,成员变量应该是私有的,而不是公共的,因为您想通过 getter 访问它(而不是通过 CommandHandler 中的 getter 访问它)。
| 归档时间: |
|
| 查看次数: |
52592 次 |
| 最近记录: |