增加一个spring mvc 的枚举转换器

用jaskson 的 注解 @JsonCreator 失效了,但是没排查出来具体原因,把我气坏了,于是写了一个转换器 先来解决项目问题。
因为我已经用接口约束了,关键值 为code 所以写死代码。
代码如下:

public class StringToEnumConverterFactory implements ConverterFactory<String, Enum> {
    @Override
    public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
        return new StringToEnum(getEnumType(targetType));
    }

    public static Class<?> getEnumType(Class<?> targetType) {
        Class<?> enumType = targetType;
        while (enumType != null && !enumType.isEnum()) {
            enumType = enumType.getSuperclass();
        }
        Assert.notNull(enumType, () -> "不是有效的枚举");
        return enumType;
    }

    private static class StringToEnum<T extends Enum> implements Converter<String, T> {

        private final Class<T> enumType;

        public StringToEnum(Class<T> enumType) {
            this.enumType = enumType;
        }

        @Override
        public T convert(String source) {
            if (source.isEmpty()) {
                return null;
            }
            source = source.trim();
            try {

                if (Arrays.stream(this.enumType.getDeclaredFields()).anyMatch(am -> {
                            String sinew = StringUtils.trimWhitespace(am.toString());
                            return sinew.length() > 5 && ".code".equals(sinew.substring(sinew.length() - 5));
                        }

                )) {
                    Method getCodeMethod = this.enumType.getDeclaredMethod("getCode");
                    for (Object obj : this.enumType.getEnumConstants()) {
                        if (source.equals(getCodeMethod.invoke(obj).toString())) {
                            return enumType.cast(obj);
                        }
                    }
                }
            } catch (Exception e) {
                return (T) Enum.valueOf(this.enumType, source);
            }
        }
    }
}

posted @ 2021-03-22 20:01  空明师兄  阅读(70)  评论(0编辑  收藏  举报