![](/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.