我有一个如下所示的类,在我设置数据之前,我需要检查getValue()是否存在以及它的值是否为空。
public class Money {
{
private String value;
private String currency;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getCurrency() {
return currency;
public void setCurrency(String currency) {
this.currency = currency;
}
}
//JSON is like this
"money": {
"currency": "USD",
"value": ""
}我想检查这个getValue()是否像obj.getMoney().getValue() != null一样存在,然后我需要检查它的值是否为空……obj.getMoney().getValue().equals(""),但在此条件下失败obj.getMoney().getValue() != null为null。
发布于 2017-01-08 14:25:25
如果以下检查失败
if (obj.getMoney().getValue() != null) { ... }那么它就意味着货币对象本身就是null。在这种情况下,您可以稍微修改您的if条件来检查:
if (obj.getMoney() != null && obj.getMoney().getValue() != null) { ... }发布于 2017-01-08 14:27:11
obj.getMoney().getValue()会给你一个空指针异常。在使用之前,您应该检查是否有空对象。在那之后。示例代码:
下面的代码看起来很大,但实际上是可读的,编译器会对其进行优化。
if(obj != null){
Money money = obj.getMoney();
if(money != null) {
String value = money.getValue();
//Add you logic here...
}
}发布于 2017-01-08 14:32:38
我认为你得到的是空点异常。您将面临此异常,因为obj.getMoney()已为空。由于您正在尝试获取空对象的值,因此您将获得此异常。正确的代码将是
if ((obj.getMoney() != null) && (obj.getMoney().getValue().trim().length() > 0)) {
// Execute your code here
}https://stackoverflow.com/questions/41530072
复制相似问题