if语句中的多个或条件
问题描述:
我已经创建了一个方法,该方法使用遍历映射的迭代器,并且对于每对来评估具有许多OR条件的语句。如果条件为真,则它将该对(通知对象)的对象添加到列表(异常)中。但是,在编译时,编译器会在此方法中提供NullPointerException异常。根据我的调查,if语句似乎存在问题,但我看不出为什么。任何人都可以给我一个帮助吗?谢谢!if语句中的多个或条件
public List<Notification> getAnomalies(NotificationSearchCriteria notificationSearchCriteria) {
Map<String,Notification> messageList = new HashMap<String,Notification>();
List<Notification> anomalies = new ArrayList<Notification>();
Iterator iterator = messageList.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry pairs = (Map.Entry)iterator.next();
Notification message = (Notification) pairs.getValue();
if(message.getDescription().equals(notificationSearchCriteria.getDescription())||message.getSubjectName().equals(notificationSearchCriteria.getSubjectName())||message.getNotificationSubject().toString().equals(notificationSearchCriteria.getNotificationSubject().toString())||message.getNotificationType().toString().equals(notificationSearchCriteria.getNotificationType().toString())){
anomalies.add(message);
}
}
}
return anomalies;
}
答
这很可能是由于message
上的一种方法返回null而引起的。例如,如果message.getDescription()
返回null,则message.getDescription().equals(<something>)
将抛出NullPointerException
,因为您无法在空对象上调用其他方法。
有几种方法可以解决这个问题。首先,我建议检查您的对象,看看哪些可以返回空值并添加适当的处理代码。
更一般地说,我总是建议在你不知道为null的变量上调用equals来避免这些问题。例如
if ("accept".equals(command)) {
// do something
}
通常优于
if (command.equals("accept")) {
// do something
}
因为通过NPE的第二个可能是,当第一永远不会。
答
我会重构消息匹配代码到NotificationSearchCriteria
类。 if
最终会成为“if(notificationSearchCriteria.matches(message))”。从名字来看,我猜测这是NotificationSearchCriteria
的唯一用法;在这个意义上说,它不会增加耦合。
检查零位将在NotificationSearchCriteria
施工期间执行;这将确保所有字段都是非空的。在该类中的匹配代码中,事情将如下所示:
boolean matches(Notification message) {
if (description.equals(message.getDescription()) || // LHS guaranteed non-null
foo.equals(message.getFoo()) ||
bar.equals(message.getBar()) || // ...
) { return true; }
}
答
代码的最佳方式是执行空检查。
理想我想有这样的代码:
while (iterator.hasNext()) {
Map.Entry pairs = (Map.Entry)iterator.next();
Notification message = (Notification) pairs.getValue();
if(null!=message && null!=message.getDescription() &&
null!=notificationSearchCriteria.getDescription())
{
//Do your comparioson
}else{
//Handle the NullPointerException error the way you want
}
}
了'if'声明之前,打印出每个对象的您正在检查('message.getDescription()','notificationSearchCriteria.getDescription() '等),以确保这些都不是“空”。我的猜测是其中之一没有被分配到某个地方。 – iamnotmaynard 2013-02-08 15:10:58
'NullPointerException'在运行时发生,**从不**在编译时。 – jlordo 2013-02-08 15:11:36
你的if语句看起来不错,但对我而言,NullPointerException听起来像是if语句中的一个对象实际上是null。我会确保notificationSearchCriteria在传递给函数时不是null,看看是否有帮助。 – 2013-02-08 15:11:59