Make ReflectionToStringBuilder skip fields with null values
I need to print the values of objects in a log file. I used:
ReflectionToStringBuilder.toString(this, ToStringStyle.MULTI_LINE_STYLE, true, true);
But it also prints null values that I don't want to include, like:
Pojo @ 117d9a3 [id = 1, name = null , description = Manchester United, KEY = APP-KEY, secretKey = Alex]
How do I prevent the inclusion of null values?
source to share
An easier solution without subclassing would be to override the accept method:
public String toStringWithAttributes() {
Object myself = this;
ReflectionToStringBuilder builder = new ReflectionToStringBuilder(
this, ToStringStyle.SHORT_PREFIX_STYLE) {
@Override
protected boolean accept(Field field) {
try {
return super.accept(field) && field.get(myself) != null;
} catch (IllegalAccessException e) {
return super.accept(field);
}
}
};
return builder.toString();
}
This has the added benefit that you can use whatever ToStringStyle
, and the formatting is otherwise perfect.
source to share
You must provide your own implementation of ToStringStyle. 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 is private
and final
, therefore, we cannot extend it. The real thing happens in the method append
. Here is the original 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);
}
source to share