0

I work on a Batch with Spring-Batch. In a processor I have to handle a DTO with approximately twenty fields.

Functionally, if no field is empty I have nothing to do. So I would like to find out in first place, if no field is empty.

But I don't really want to do an "if" with twenty

DTO.getValue1 != null && DTO.getValue2 != null [...]

I wonder if there will not be a cleaner way to do that ?

thx in advance.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
M_B
  • 3
  • 2

1 Answers1

1

You can use reflection for validation purposes. Define an isNull method in the DTO to check for null fields.

public boolean isNull() {
        Field fields[] = this.getClass().getDeclaredFields();
        for (Field f : fields) {
            try {
                Object value = f.get(this);
                if (value != null) {
                    return false;
                }
            }
            catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        }
        return true;

    }
dassum
  • 4,727
  • 2
  • 25
  • 38
  • Yeah thx functionnaly is more: ```java if (value == null) { return false; } ``` But I have my answer. – M_B Sep 06 '19 at 09:44