简体   繁体   中英

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.

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.

If the following check fails

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

then it implies that the money object itself is null . In this case, you can slightly modify your if condition to check for this:

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

obj.getMoney().getValue() will give you null pointer exception. You should check for null object before using . 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. Since you are trying to get a null object's value, so you are getting this exception. 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,

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. The form of validation is correct, the problem is in the obj that was not initialized. (I believe)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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