I am trying to make a Utility method where if i pass an object and return true or false if its all fields and child objects are null or not respectively. Below is the code snippet i am trying. In real time the objects will have primitive and non primitive type fields. How i can achieve this functionality.
public static void main(String[] args) {
var test = new Testing();
System.out.println(ObjectUtils.isAllNull(test));
}
public class Testing {
Testin2 testin2 = new Testin2();
}
public class Testin2 {
}
ObjectUtils {
public static boolean isAllNull(Object target) {
return Arrays.stream(target.getClass()
.getDeclaredFields())
.peek(f -> f.setAccessible(true))
.map(f -> getFieldValue(f, target))
.allMatch(Objects::isNull);
}
private static Object getFieldValue(Field field, Object target) {
try {
return field.get(target);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}