1

I have a class with about 20 members and I have a method to validate that 10 specific members are not null. At first I thought none of them could be null so I was doing a for loop through this.getClass().getDeclaredFields() but when I learned that 10 of them could actually be null, that plan failed.

I tried googling if there was a way of setting subsets of members and looping through those only, but didn't find anything useful. Otherwise I'm left with a big if ((id == null) || (type == null) ... return false

Any ideas to do this in a cleaner way?

coconut
  • 1,074
  • 4
  • 12
  • 30
  • 2
    Can you show a [mcve] of the problem? Is there a specific need to check if so many fields are all null at once? – OneCricketeer Jan 23 '18 at 15:17
  • 4
    It depends on exactly what you want to do. If indeed you want to do precisely what you say -- validate that ten specific members are non-null -- then the easiest and best thing to do is test them explicitly by name. Yes, the code is a little tedious, but it is clear, and it is furthermore likely to be lest costly than a reflective solution. – John Bollinger Jan 23 '18 at 15:18
  • @cricket_007 I'm getting a request as a JSON and turning it into an object with jackson but business logic wants me to give a specific exception if some members are null. – coconut Jan 23 '18 at 15:21
  • 2
    Basically, 20 fields is too many. You should break your class down into smaller parts. Nullable fields often result in ugly code. If there is some condition where a field may or may not be null, that's a potential candidate for having two classes which implement the same interface. – Michael Jan 23 '18 at 15:21
  • 1
    You may want to use Java Validation API, an example here : http://www.baeldung.com/javax-validation – Arnaud Jan 23 '18 at 15:23
  • @coconut, you can't throw a specific exception if you use a `(id == null) || (type == null)`, why don't you validate these fields in some order? – Andrew Tobilko Jan 23 '18 at 15:24
  • @AndrewTobilko I meant a specific code for the case any of them are null. – coconut Jan 23 '18 at 15:26

1 Answers1

2

You can create an annotation to mark the fields that are not null and then just filter the list of fields according to the annotation

public class ValidateNotNullProperty
{
    public static @interface NotNull {}

    // example usage
    @NotNull
    public int id;

    public static List<Field> getMandatoryFields(Class<?> cls) {
        return Arrays.asList(cls.getDeclaredFields()).stream()
        .filter(fld -> fld.isAnnotationPresent(NotNull.class))
        .collect(Collectors.toList());
    }
}
Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47