Search code examples
javaif-statementpojocode-cleanup

Concat all nonNull properties of a POJO


I have a POJO which has 10-15 fields(can be primitive,Custom Object or String). I want to concat all the NonNull fields in a String.

Is there any clean way to do without using 10-15 if statements.


Solution

  • You could use Reflection:

    Foo foo = new Foo(3, 89, null);
    
    Field[] fields = foo.getClass().getDeclaredFields();
    
    for(Field field: fields) {
        Object fieldValue = field.get(foo);
        if(fieldValue != null) {
            // Do your actual logic here
            System.out.println(fieldValue);
        }
    }
    

    with a Foo class like this:

        static class Foo {
            int bar;
            int barre;
            String barString;
    
            public Foo(int bar, int barre, String barString) {
                this.bar = bar;
                this.barre = barre;
                this.barString = barString;
            }
        }
    

    note: this is assuming that you can access the fields in Foo, if they are private then you have to use getters instead.