Check some members are not null

319 Views Asked by At

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?

1

There are 1 best solutions below

2
Sharon Ben Asher On

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());
    }
}