我在构造函数中初始化了一个变量,但当我尝试在另一个方法中使用它时它仍然为空

I initialized a variable inside of a constructor, but it's still null when I try to use it in another method

这是构造函数

private ActionbarTitleObject timer = TitleFactory.newBarTitle("");
private Plugin plugin;
HashMap<String, Parkour> parkours = null;

public MineJump() {}

public MineJump(ArrayList<Player> players, String configPath, Plugin plugin)
{
    super(players);
    this.plugin = plugin;
    parkours = Parkour.load(configPath, players);
    System.out.println(parkours.get("p1").getCurrentSpawn()); //here I get the right value
}

但是当我尝试在此方法中使用跑酷哈希图时

@EventHandler
public void onPlayerMove(PlayerMoveEvent e)
{
    System.out.println(parkours.get("p1").getCurrentSpawn()); //parkours is null here :(
}

我收到 NullPointerException。这是为什么?

我使用非参数构造函数仅用于此:Bukkit.getPluginManager().registerEvents(new MineJump(), this);

这会导致错误吗?如果是的话,如果你能向我解释为什么会很好。 :)

一个可能的解释是 onPlayerMove 在构造函数

中调用 super() 时作为副作用结果被调用

正如您所解释的,您使用了无参数构造函数。此构造函数不会将 parkours 设置为不同于 null 的值。

您需要使用带有如下参数的第二个构造函数:

Bukkit.getPluginManager().registerEvents(new MineJump(players, configPath, plugin), this);