Bukkit Java NullPointer 在检查某物是否为空时

Bukkit Java NullPointer when checking if something is null

我正在使用 Bukkit API 1.8.3

我有这段代码:

for(String vey : main.getConfig().getConfigurationSection("shopitems."+key+".enchantments").getKeys(false))
{
    Enchantment ench = Enchantment.getByName(vey);
    int level = main.getConfig().getInt("shopitems."+key+".enchantments."+vey);
    meta.addEnchant(ench, level, true);
}

这段代码为我提供了一个指向开始 for 循环迭代的行的空指针。

尝试解决这个问题我有一个空检查器:

if(main.getConfig().getConfigurationSection("shopitems."+key+".enchantments").getKeys(false)!=null)

在这个空检查器之后,我将上面的代码放在这个 if 语句中。

但是我在测试该路径是否为空的行上得到一个空指针

我的问题:为什么这不起作用,我该如何解决

注意:main.getConfig() returns FileConfiguration 不为 null 我已经测试了一个已调试的

if(main.getConfig().getConfigurationSection("shopitems."+key+".enchantments").getKeys(false)!=null)

是错误的,因为当您尝试 getKeys(false) 它时 returns 为空,因为 getConfigurationSection() 已经为空。您可以通过以下方式解决此问题:

if(main.getConfig().getConfigurationSection("shopitems."+key+".enchantments") !=null);