開発メモ

開発用のメモです。

ToString 実行時に null 値を除外する。

import java.lang.reflect.Field;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class ToStringBuilder extends ReflectionToStringBuilder {

    private static final Logger logger = LogManager.getLogger(ToStringBuilder.class);

    public ToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer) {
        super(object, style, buffer);
    }

    public ToStringBuilder(Object object, ToStringStyle style) {
        super(object, style);
    }

    public ToStringBuilder(Object object) {
        super(object, ToStringStyle.SHORT_PREFIX_STYLE);
    }

    public <T> ToStringBuilder(T object, ToStringStyle style, StringBuffer buffer, Class<? super T> reflectUpToClass,
            boolean outputTransients, boolean outputStatics) {
        super(object, style, buffer, reflectUpToClass, outputTransients, outputStatics);
    }

    @Override
    protected boolean accept(Field field) {
        try {
            return super.accept(field) && super.getValue(field) != null;
        } catch (IllegalArgumentException | IllegalAccessException e) {
            logger.warn(e.getMessage(), e);
        }
        return false;
    }

}
Twitter: @asahina_alice