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]
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 ]
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