我有一段简单的代码:
txtRequiredDate.setText(wwDateFormatter.format(todoEntity.getRequiredDate()));
txtRequiredDateDay.setText(dayOfWeek(todoEntity.getRequiredDate()));
txtDoneDate.setText(wwDateFormatter.format(todoEntity.getDoneDate()));
txtDoneDateDay.setText(dayOfWeek(todoEntity.getDoneDate()));
问题是有时日期为空(因为它是可选的填写)。在这些情况下,wwDateFormatter 会触发 NullPointerException。
正如我所见,修复它的一种方法是:
if (todoEntity.getRequiredDate() != null)
{
txtRequiredDate.setText(wwDateFormatter.format(todoEntity.getRequiredDate()));
txtRequiredDateDay.setText(dayOfWeek(todoEntity.getRequiredDate()));
}
if (todoEntity.getDoneDate() != null)
{
txtDoneDate.setText(wwDateFormatter.format(todoEntity.getDoneDate()));
txtDoneDateDay.setText(dayOfWeek(todoEntity.getDoneDate()));
}
但我想知道是否有更简洁的方式来编写上述语句?
谢谢你!
编辑我想这不是没有优化,而是我想学习各种检查空值的方法,特别是如果出现我必须有 30 个这样的语句的情况,呵呵。