java.lang.NullPointerException: 无法读取数组长度,因为“<local3>”为空

java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

我正在开发 JDA Discord Bot,每次我 运行 它时,我都会得到这个异常。

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)

我试图制作一个基本的命令处理程序,这里是它的代码:

 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);
            }
        }
    }

Index.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"
        };
    }
}

我不确定为什么会导致异常。谢谢!

编辑:这是我的 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();
        }
    }
}

您的 Index class 中有一个成员变量 public String[] indexClass。在您的构造函数中,您使用

创建一个新变量
String[] indexClass = {
        "com.houseofkraft.command.Ping",
        "com.houseofkraft.command.Test"
};

这样你的成员变量就会保持未初始化状态。将构造函数中的代码更改为

this.indexClass = {
        "com.houseofkraft.command.Ping",
        "com.houseofkraft.command.Test"
};

顺便说一句,成员变量应该是私有的,而不是 public,因为你想通过 getter 访问它(而不是通过 CommandHandler 中的 getter 访问它) .