Let's assume I have an object with x amount of fields. Two are allowed to be non-null and the rest has to be null. I don't want to do a null check field by field, so I wonder if there is a smart way to do this null check with some of the features of the latest java versions.
You can create stream
for all the fields in POJO and can check for null
return Stream.of(id, name).anyMatch(Objects::isNull);
or
return Stream.of(id, name).allMatch(Objects::isNull);
If there are only a few fields in the object, and you know it won't change frequently, you could list them as Stream.of
arguments as per Deadpool's answer. The drawback is violation of the DRY principle: you are repeating the field names: once in the POJO definition and again in the argument list.
If you have many fields (or don't want to repeat yourself) you could use reflection:
boolean valid = Stream.of(YourPojoClass.class.getDeclaredFields())
.filter(f -> !(f.getName().equals("fieldname allowed to be null") || f.getName.equals("the other field name")))
.allMatch(f -> {
f.setAccessible(true);
try {
return f.get(o) == null;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
});
Note that use of reflection can have a small performance penalty, likely to be insignificant compared to parsing a JSON string obtained from a web service.
If you have primitive fields (e.g. int
, boolean
, char
) and you want to include them in the checks, restricting them to default values (0
, false
, '\0'
) then use the following code:
.allMatch(f -> {
f.setAccessible(true);
try {
return (f.getType() == boolean.class && f.getBoolean(o) == false)
|| (f.getType().isPrimitive() && f.getDouble(o) == 0)
|| f.get(o) == null;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With