• 增加一个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);
                }
            }
        }
    }
    
    
  • 相关阅读:
    java_十进制数转换为二进制,八进制,十六进制数的算法
    vim常用命令 vim键盘布局
    百度HTTPS加密搜索有什么用?
    delete
    hadoop2的automatic HA+Federation+Yarn配置的教程
    MinGW GCC下sleep()函数问题
    delete
    8天学通MongoDB——第一天 基础入门
    8天学通MongoDB——第六天 分片技术
    8天学通MongoDB——第五天 主从复制
  • 原文地址:https://www.cnblogs.com/akashicbrother/p/14567391.html
Copyright © 2020-2023  润新知