[英]Java - getMethod null check
我有一个如下所示的类,在设置数据之前我需要检查是否存在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。
如果以下检查失败
if (obj.getMoney().getValue() != null) { ... }
那意味着货币对象本身就是null
。 在这种情况下,您可以稍微修改if
条件以检查:
if (obj.getMoney() != null && obj.getMoney().getValue() != null) { ... }
obj.getMoney()。getValue()将为您提供空指针异常。 您应该在使用之前检查null对象。 在它之后。 示例代码:
下面的代码看起来很大,但它实际上是可读的,它将由编译器优化。
if(obj != null){
Money money = obj.getMoney();
if(money != null) {
String value = money.getValue();
//Add you logic here...
}
}
我认为你得到零点异常。 您正面临此异常,因为obj.getMoney()已为空。 由于您尝试获取null对象的值,因此您将获得此异常。 正确的代码将是
if ((obj.getMoney() != null) && (obj.getMoney().getValue().trim().length() > 0)) {
// Execute your code here
}
你说首先需要检查value
是否为null,然后检查值是否为空,
您可以执行以下操作
if (obj.getMoney() != null && obj.getMoney().getValue() != null && !obj.getMoney().getValue().isEmpty()) {
// rest of the code here
}
在实例化你的obj时,给出一个新的。 验证的形式是正确的,问题出在未初始化的obj中。 (我相信)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.