Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache Commons toString utility that only includes fields that have value

Is there a toString utility from Apache Commons that will only include in the resulting toString value those fields that are NOT null?

For example:

public class Person {
String name;
String height;
String age;
}

And create an instance where it has a name and age. Then calling the utility for example:

utility.toStringNonNull(person);

Will output:

[name=Mary, age=28]

like image 347
Carlos Jaime C. De Leon Avatar asked Jun 19 '13 11:06

Carlos Jaime C. De Leon


1 Answers

I was able to do this by extending Apache's ToStringStyle class:

public static class TestStyle extends ToStringStyle{
    TestStyle() {//constructor is copied from ToStringStyle.MULTI_LINE_STYLE
        super();
        this.setContentStart("[");
        this.setFieldSeparator(SystemUtils.LINE_SEPARATOR + "  ");
        this.setFieldSeparatorAtStart(true);
        this.setContentEnd(SystemUtils.LINE_SEPARATOR + "]");
    }

//override this to do checking of null, so only non-nulls are printed out in toString
@Override
public void append(StringBuffer buffer, String fieldName, Object value, Boolean fullDetail) {
    if (value != null) {
        super.append(buffer, fieldName, value, fullDetail);
    } 
}

Then use is like this:

public static void main(String[] args) {
    Person p = new Person();
    p.setName("Tester");
    ToStringStyle style = new TestStyle();

    System.out.println("toString = " + ToStringBuilder.reflectionToString(p, style));

}

This will result into: Person@37403a09[ name=Tester ]

like image 137
Carlos Jaime C. De Leon Avatar answered Oct 10 '22 13:10

Carlos Jaime C. De Leon