![](/img/trans.png)
[英]How to check the variables of an Object are Empty or NULL in JAVA?
[英]Null empty check for Custom Object in Java
我有以下空检查金额有以下字段
Amount{
Money amountToBePaid;
Float percentage;
}
和 Money 有以下字段:
Money {
String unit;
BigDecimal value
}
private boolean checkIfAmountDefined(Amount amount){
amountFlag=false;
If (null != amount || !ObjectUtils.isEmpty(amount)) {
if (!ObjectUtils.isEmpty(amount.getAmountToBePaid())&&
!ObjectUtils.isEmpty(amount.getPercentage())) {
if (!ObjectUtils.isEmpty(amount.getAmountToBePaid().getValue()) ||
!ObjectUtils.isEmpty(amount.getAmountToBePaid().getUnit())) {
amountFlag = true;
return amountFlag;
}
}
}
return amountFlag;
}
我需要检查是否未定义我在 c check 下运行的金额。问题是我有时使用百分比,有时使用其他字段获得空指针异常。 我不能忽略任何内部字段,因为基于这些字段,我将考虑是否定义了金额。 有什么建议吗?
你的第一个 if If (null != Amount || !ObjectUtils.isEmpty(Amount))
应该是
if (null != Amount && null != Amount.getAmountToBePaid() && !ObjectUtils.isEmpty(Amount))
当您稍后使用它们时,这可确保您不会得到null pointer exception
,只要ObjectUtils.isEmpty(...)
适当地处理null
。
如果该方法根据这些条件返回一个布尔值,我将return true;
如果它通过所有这些 if 语句进行管理,则return false;
最后完成你的boolean
return
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.