NullPointerException thrown after field is check if it is null

房东的猫 提交于 2019-12-13 09:16:19

问题


I am developing a plugin for Bukkit (http://bukkit.org) and after verifying that it is not null, it gives me a NullPointerException at the 2nd line

    String description = getConfig().getString("core.commands."+cmd+".description");
    if (!(description.isEmpty()))
          getCommand(cmd).setDescription(description);
    else 
          getLogger().warning("NO description assigned to: " + cmd);
    description = null;

回答1:


isEmpty() is different from null check. isEmpty() checks is String is empty String (which means "").

You need to do something like

if (description != null && !description.isEmpty())



回答2:


Your code !(description.isEmpty()) doesn't verify that description is not null. For that you need description != null.

Your test should be:

if (description != null && !description.isEmpty()) ...



回答3:


I suspect the problem isn't in the if condition - but in the statement that follows. I would start by reformatting the code like this:

String description = getConfig().getString("core.commands." + cmd + ".description");
if (!description.isEmpty())
{
    getCommand(cmd).setDescription(description);
}
else
{
    getLogger().warning("NO description assigned to: " + cmd);
}

(I've removed the description = null; statement as it's almost certainly unnecessary.)

With that change, you'll be able to tell more about what's throwing the exception. You can go further:

String description = getConfig().getString("core.commands." + cmd + ".description");
if (!description.isEmpty())
{
    Command command = getCommand(cmd); // Or whatever type it is
    command.setDescription(description);
}
else
{
    getLogger().warning("NO description assigned to: " + cmd);
}

Aside from anything else, when you now step through the code in a debugger (assuming that's even feasible) you'll be able to tell whether command is null (which I suspect it is). If you can't use a debugger, you could at least add logging.

(Others have already suggested checking whether description is null, but it sounds like that isn't the problem, which is why I've suggested that the problem could be within the body of the if statement.)



来源:https://stackoverflow.com/questions/18665495/nullpointerexception-thrown-after-field-is-check-if-it-is-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!