Concat all nonNull properties of a POJO

Viewed 283

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.

3 Answers

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.

if that is just a String then you can concatenate then and replace the word null with empty space, BUT be careful with the appending chars used to append the fields(you dont want to see something like john,,,22,,,true)

check this example

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        String x = null;
        String a="Hello";
        Long l1=null;
        Long l2=55L;

        String r=a+x+l1+l2;
        r=r.replace("null", "-");
        System.out.println(r);
    }
}

this will print

Hello--55

You can set all the Strings as "" by default:

class SomeObject {
    private String field1 = "";
    private String field2 = "";

    //constructor, getters and setters

    @Override
    public String toString() {
        return field1 + field2;
    }
}

Or do it in the constructor:

class SomeObject {
    private String field1;
    private String field2;

    public SomeObject(String string1, String string2) {
        this.field1 = string1 == null ? "" : string1;
        this.field2 = string2 == null ? "" : string2;
    }

    //getters and setters

    @Override
    public String toString() {
        return field1 + field2;
    }
}

Alternatively you can modify the getters to return a "" when a String is null and use getters instead of direct var calls in your concat method.

class SomeObject {
    private String field1;
    private String field2;

    // constructor and setters

    public String getField1() {
        return field1 == null ? "" : field1;
    }

    public String getField2() {
        return field2 == null ? "" : field2;
    }

    @Override
    public String toString() {
        return getField1() + getField2();
    }
}
Related