NullPointerException thrown after field is check i

2019-09-21 04:16发布

问题:

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.)