You have to provide your own ToStringStyle implementation. Something like this (untested!):
import org.apache.commons.lang.SystemUtils;
import org.apache.commons.lang.builder.ToStringStyle;
public final class NotNullToStringStyle extends ToStringStyle {
public static final ToStringStyle NOT_NULL_STYLE = new NotNullToStringStyle();
private static final long serialVersionUID = 1L;
/**
* <p>Constructor.</p>
*
* <p>Use the static constant rather than instantiating.</p>
*/
NotNullToStringStyle() {
super();
this.setContentStart("[");
this.setFieldSeparator(SystemUtils.LINE_SEPARATOR + " ");
this.setFieldSeparatorAtStart(true);
this.setContentEnd(SystemUtils.LINE_SEPARATOR + "]");
}
/**
* <p>Ensure <code>Singleton</code> after serialization.</p>
*
* @return the singleton
*/
private Object readResolve() {
return NOT_NULL_STYLE;
}
@Override
public void append(StringBuffer buffer, String fieldName, Object value, Boolean fullDetail) {
if (value != null) {
appendFieldStart(buffer, fieldName);
appendInternal(buffer, fieldName, value, isFullDetail(fullDetail));
appendFieldEnd(buffer, fieldName);
}
}
}
Most of the code is copied from MultiLineToStringStyle, since it's private and final so we can't extend it. The real thing happens in the append method. Here is the original one for reference:
public void append(StringBuffer buffer, String fieldName, Object value, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (value == null) {
appendNullText(buffer, fieldName);
} else {
appendInternal(buffer, fieldName, value, isFullDetail(fullDetail));
}
appendFieldEnd(buffer, fieldName);
}