What's the best way to register a Converter for all subclasses of a particular class when using Commons BeanUtils?

梦想的初衷 提交于 2019-12-05 16:44:36

You can override ConvertUtilsBean. The following code adds support for Enum, but you can do the same for Map:

BeanUtilsBean.setInstance(new BeanUtilsBean(new EnumAwareConvertUtilsBean()));

Class definitions:

public class EnumAwareConvertUtilsBean extends ConvertUtilsBean2 {

    private static final EnumConverter ENUM_CONVERTER = new EnumConverter();

    @Override
    public Converter lookup(Class pClazz) {
        final Converter converter = super.lookup(pClazz);

        if (converter == null && pClazz.isEnum()) {
            return ENUM_CONVERTER;
        } else {
            return converter;
        }
    }

}

public class EnumConverter extends AbstractConverter {

    private static final Logger LOGGER = LoggerFactory.getLogger(EnumConverter.class);

    @Override
    protected String convertToString(final Object pValue) throws Throwable {
        return ((Enum) pValue).name();
    }

    @Override
    protected Object convertToType(final Class pType, final Object pValue)
        throws Throwable
    {
        // NOTE: Convert to String is handled elsewhere

        final Class<? extends Enum> type = pType;
        try {
            return Enum.valueOf(type, pValue.toString());
        } catch (final IllegalArgumentException e) {
            LOGGER.warn("No enum value \""
                + pValue
                + "\" for "
                + type.getName());
        }

        return null;
    }

    @Override
    protected Class getDefaultType() {
        return null;
    }

}

I got the solution from reading the blog post and comments from http://www.bitsandpix.com/entry/java-beanutils-enum-support-generic-enum-converter/

Was trying to to the same thing (my use case was a common converter for all type of Enum) but from what I could see in the code ConvertUtils only support direct mapping between converter and class and there is no way to register a base class or an interface.

Basically it's using a Map where the key is the class and the value the converter and to get the proper converter based in the class it simply does a Map#get.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!