Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking null fields of an object in JAVA

Tags:

java

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.

like image 881
KingMetin2 Avatar asked Sep 03 '25 15:09

KingMetin2


2 Answers

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);
like image 74
Deadpool Avatar answered Sep 05 '25 06:09

Deadpool


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);
        }
    });
like image 32
DodgyCodeException Avatar answered Sep 05 '25 07:09

DodgyCodeException