Skip to content
Advertisement

count non-null numbers of an object

I am making a method that can count non null value of an object, but I have an object inside another object and I have to confirm if that object is empty too, I tried with isEmpty, isNull but it says it is not empty.

Object

public class ExceptionDTO {

    private ResultExceptionDTO result;
    
    private String param;
    
    private String content;
}

Validation method

 public static <T> void validChoice(Object request, Class<T> clazz) throws Exception {
        int nonNullCount = 0;
        for (Field field : clazz.getDeclaredFields())
        {
            field.setAccessible(true);
            if (field.get(request) != null || !ObjectUtils.isEmpty(field.get(request)))
            {
                System.out.println(field.get(request));
                nonNullCount++;
            }
        }

        if (nonNullCount != 1) {
            throw new ValidationException(ERROR_MISSING_PARAMS);
        }

    }

I have also tried with !ObjectUtils.isNull...

Even though the “result” object has no values it says that it is not empty`

Setter

ResultExceptionDTO result = new ResultExceptionDTO();

ExceptionDTO dto = new ExceptionDTO();
dto.setParam("param");
dto.setResult(result);

validChoice(dto, ExceptionDTO.class);

Here it should not show me “result” as different from null, because so far there is the instance of the class “ResultExceptionDTO” with its null attributes

Advertisement

Answer

Here is the method that works:

    public static long countNullFields(Object o){
        return Arrays.stream(o.getClass().getDeclaredFields())
                .map(field -> {
                    try {
                        field.setAccessible(true);
                        return field.get(o);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                    throw new IllegalArgumentException();
                })
                .filter(Objects::isNull)
                .count();
    }
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement