检查某些内容是否为空时,Bukkit Java NullPointer

时间:2015-07-30 07:38:37

标签: java null nullreferenceexception bukkit

我使用的是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);
}

这段代码给了我一个nullpointer,指向启动for循环迭代的行。

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

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

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

但是我在测试该路径为空的行

上得到一个nullpointer

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

注意:返回FileConfiguration的main.getConfig()不为null我已经测试过调试了这个

1 个答案:

答案 0 :(得分:0)

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

错误,因为当您尝试getKeys(false)时,它返回null,因为getConfigurationSection()已经为空。你可以通过以下方式解决这个问题:

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