简体   繁体   English

Java - getMethod null检查

[英]Java - getMethod null check

I have a class as below, before I set the data I need to check whether getValue() is present and it's value is empty. 我有一个如下所示的类,在设置数据之前我需要检查是否存在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": ""
}

I want to check whether this getValue() is present or not like obj.getMoney().getValue() != null , and then I need to check it's value is empty... obj.getMoney().getValue().equals("") but it fails on this condition obj.getMoney().getValue() != null as null. 我想检查这个getValue()是否存在,如obj.getMoney().getValue() != null ,然后我需要检查它的值是否为空... obj.getMoney().getValue().equals("")但在这个条件下失败obj.getMoney().getValue() != null为null。

If the following check fails 如果以下检查失败

if (obj.getMoney().getValue() != null) { ... }

then it implies that the money object itself is null . 那意味着货币对象本身就是null In this case, you can slightly modify your if condition to check for this: 在这种情况下,您可以稍微修改if条件以检查:

if (obj.getMoney() != null && obj.getMoney().getValue() != null) { ... }

obj.getMoney().getValue() will give you null pointer exception. obj.getMoney()。getValue()将为您提供空指针异常。 You should check for null object before using . 您应该在使用之前检查null对象。 after it. 在它之后。 Example code: 示例代码:

Below code looks huge but it's actually readable and it will be optimized by compiler. 下面的代码看起来很大,但它实际上是可读的,它将由编译器优化。

if(obj != null){
    Money money = obj.getMoney();
    if(money != null) {
        String value = money.getValue();
        //Add you logic here...
    }
}

I think you are getting null point exception. 我认为你得到零点异常。 You are facing this exception because obj.getMoney() is already null. 您正面临此异常,因为obj.getMoney()已为空。 Since you are trying to get a null object's value, so you are getting this exception. 由于您尝试获取null对象的值,因此您将获得此异常。 Correct code will be 正确的代码将是

if ((obj.getMoney() != null) && (obj.getMoney().getValue().trim().length() > 0)) { 
    // Execute your code here
}

You said that first you need to check whether value is null or not and then also check whether the value is empty or not, 你说首先需要检查value是否为null,然后检查值是否为空,

You can do the following 您可以执行以下操作

if (obj.getMoney() != null && obj.getMoney().getValue() != null && !obj.getMoney().getValue().isEmpty()) {
      // rest of the code here
}

When instantiating your obj, gives a new. 在实例化你的obj时,给出一个新的。 The form of validation is correct, the problem is in the obj that was not initialized. 验证的形式是正确的,问题出在未初始化的obj中。 (I believe) (我相信)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM