Java 条件中main()上的NullPointerException

Java 条件中main()上的NullPointerException,java,nullpointerexception,Java,Nullpointerexception,我正在尝试运行以下命令:PGDirTestController.performExecute()调用performExecute()方法,该方法应属于performExecute()中的else{},该方法最终调用callUSInterface() 不幸的是,这会引发NullPointerException: Exception in thread "main" java.lang.NullPointerException at com.XX.commerce.bes.member.te

我正在尝试运行以下命令:
PGDirTestController.performExecute()
调用
performExecute()
方法,该方法应属于
performExecute()
中的
else{}
,该方法最终调用
callUSInterface()

不幸的是,这会引发NullPointerException:

Exception in thread "main" java.lang.NullPointerException
    at com.XX.commerce.bes.member.test.commands.XXGetProgramGuideDirectTestControllerCmdImpl.performExecute(XXGetProgramGuideDirectTestControllerCmdImpl.java:51)
    at com.XX.commerce.bes.member.test.commands.XXGetProgramGuideDirectTestControllerCmdImpl.main(XXGetProgramGuideDirectTestControllerCmdImpl.java:199)
XXGetProgramGuideDirectTestControllerCmdImpl的第51行是:

if (getRequestProperties().getString(XXMessagingConstants.STORE_ID).equals(XXMessagingConstants.DE_STORE_ID)) {
PGDirTestController.performExecute();
XXGetProgramGuideDirectTestControllerCmdImpl的第199行是:

if (getRequestProperties().getString(XXMessagingConstants.STORE_ID).equals(XXMessagingConstants.DE_STORE_ID)) {
PGDirTestController.performExecute();
有人知道我做错了什么以及如何纠正吗


我对java还是相当陌生。

这个表达式可能返回
null

getRequestProperties().getString(XXMessagingConstants.STORE_ID)
您可能应该为该场景添加一个单独的检查。你可以改变这种状况:

if (XXMessagingConstants.DE_STORE_ID.equals(getRequestProperties().getString(XXMessagingConstants.STORE_ID))
如@Stefan Beike所述。这将使这个空案例成为一个不相等的值。或者,当您得到
null
时,您可能想做一些完全不同的事情,因此您可以做如下操作

if (getRequestProperties().getString(XXMessagingConstants.STORE_ID) == null)
    log.wanr("request parameter is Null, this shouldn't be this way");
else if (XXMessagingConstants.DE_STORE_ID.equals(getRequestProperties().getString(XXMessagingConstants.STORE_ID)) 
    ....

在我看来,如果条件是这样的,最好使用

if (XXMessagingConstants.DE_STORE_ID.equals(getRequestProperties().getString(XXMessagingConstants.STORE_ID)) {

这是空保存

您可以通过交换正在检查的字符串来避免NPE

if (XXMessagingConstants.DE_STORE_ID.equals(getRequestProperties().getString(XXMessagingConstants.STORE_ID)) {

有关详细信息,请检查equals()方法的API引用。

PGDirtTestController必须为null。。。重新检查它是否已按预期进行初始化。您是否可以使用调试器并处理nullpointer?is
getRequestProperties()=null
getRequestProperties().getString(XXMessagingConstants.STORE_ID)=null
?一个好的做法是始终将常量放在equals等的开头。这既可以避免NPE,又可以清楚地说明所比较的内容,因为第一部分总是相同的。Great point@SimonVerhoeven感谢您的建议,这并不能解决问题,但可能对性能更好。谢谢。如果这不能解决这个问题,那么你的getRequestProperties本身将返回null。你能详细说明一下“单独检查”吗?谢谢你在这里回答这个问题。