Home > other >  Validating if multiple java object fields is not null
Validating if multiple java object fields is not null

Time:09-22

I want to check if the mandatory fields(name, age & postcode) contains value or is not null.

Typical way is

        Person person = new Person();
        person.setName("Cookie");
        person.setAge(20);

//validation
    if(person.getAge() != null && person.getName() != null){
        return true;
    }

In my original class I have over 20 fields that needs to be checked, therefore I'm wondering if there is a more elegant way of doing this?

Simple POJO class example:

public class Person {
 
   String name;
 
   int age;
 
   String address;
 
   int postcode;
 
   public Person() {
   }
 
   public String getName() {
      return this.name;
   }
 
   public void setName(String value) {
      this.name = value;
   }
 
//...etc setter and getters
}

CodePudding user response:

You could you the javax.validation. You can annotate your object with NotNull annotations. Then you can check it with a Validator.

See this example.

CodePudding user response:

Given that all your getters return a reference type (no primitives) and that you need to check only wether the result is null or not null, you can try this:

...
List<Supplier<Object>> m_Getters = new ArrayList<>();
...

public Person()
{
    m_Getters.add( this::getName );
    m_Getters.add( this::getAge ); // getAge() must return Integer, not int!!!
    m_Getters.add( this::getAddress );
    ...
 }

 ...

 public final boolean validate()
 {
      return m_Getters.stream().allMatch( s -> s.get() != null );
 }
  • Related