learning_record_doc/java/工具类/枚举工具类.md
2022-08-11 18:10:37 +08:00

6.5 KiB
Raw Blame History

枚举工具类

EnumCodeService

作用枚举Service 对实现此接口的枚举实现序列化以及其他功能
@JsonDeserialize(using = EnumCodeDeserializer.class) //jackson注解
@JsonSerialize(using = EnumCodeSerializer.class)	//jackson注解
public interface EnumCodeService {
    /**
     * 获取状态吗
     * @return
     */
    Integer getCode();

    /**
     * 获取Name
     * @return
     */
    String getName();
}

EnumCodeUtil

作用:枚举工具类
public class EnumCodeUtil {
    public static <E extends Enum<E> & EnumCodeService> E manageCode(Class<E> enumClass, int code) {
        E[] enumConstants = enumClass.getEnumConstants();
        for (E e : enumConstants) {
            if (e.getCode() == code) {
                return e;
            }
        }
        return null;
    }

    public static <E extends Enum<E> & EnumCodeService> E convert(Class<E> enumClass, String str) {
        E[] enumConstants = enumClass.getEnumConstants();
        for (E e : enumConstants) {
            if (e.toString() .equals(str.toUpperCase()) ||e.getName().equals(str.toLowerCase()) || String.valueOf(e.getCode()).equals(str)) {
                return e;
            }
        }
        throw new CommonException(enumClass.getName()+"枚举不存在");
    }

    public static List<Map<String, Object>> enumToListMap(Class<?> clazz) {
        List<Map<String, Object>> resultList = null;
        // 判断是否是枚举类型
        if ("java.lang.Enum".equals(clazz.getSuperclass().getCanonicalName())) {
            resultList = new ArrayList<>();
            // 获取所有public方法
            Method[] methods = clazz.getMethods();
            List<Field> fieldList = new ArrayList<>();
            for (int i = 0; i < methods.length; i++) {
                String methodName = methods[i].getName();

                // 找到枚举类中的以get开头的(并且不是父类已定义的方法)所有方法
                if (methodName.startsWith("get") && !"getDeclaringClass".equals(methodName)
                        && !"getClass".equals(methodName)) {
                    Field field = null;
                    try {
                        // 通过方法名获取自定义字段
                        field = clazz.getDeclaredField(StringUtils.uncapitalize(methodName.substring(3)));
                    } catch (NoSuchFieldException | SecurityException e) {
                        e.printStackTrace();
                    }
                    // 如果不为空则添加到fieldList集合中
                    if (field != null) {
                        fieldList.add(field);
                    }
                }
            }
            // 判断fieldList集合是否为空
            if (!fieldList.isEmpty()) {
                Map<String, Object> map = null;
                // 获取所有枚举
                Enum<?>[] enums = (Enum[])clazz.getEnumConstants();
                for (int i = 0; i < enums.length; i++) {
                    map = new HashMap<>();
                    for (int l = 0, len = fieldList.size(); l < len; l++) {
                        Field field = fieldList.get(l);
                        field.setAccessible(true);
                        try {
                            //如果字段名称等于则跳过 非必要判断可不写
                            if (field.getName().equals("cls")){
                                continue;
                            }
                            // 向map集合添加字段名称 和 字段值
                            map.put(field.getName(), field.get(enums[i]));
                        } catch (IllegalArgumentException | IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                    map.put("enumValue",enums[i].toString());
                    // 将Map添加到集合中
                    resultList.add(map);
                }
            }
        }
        return resultList;
    }
}

EnumCodeSerializer

作用基于jackson实现枚举序列化规则
public class EnumCodeSerializer<T extends Enum & EnumCodeService> extends JsonSerializer<T> {
    @Override
    public void serialize(T t, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(t.getCode().toString());
    }
}

EnumCodeDeserializer

作用基于jackson实现枚举反序列化规则
@Slf4j
public class EnumCodeDeserializer<E extends Enum & EnumCodeService> extends JsonDeserializer<E> {
    @Override
    public E deserialize(
            JsonParser jsonParser,
            DeserializationContext deserializationContext
    ) throws IOException {
        Class c = jsonParser.getCurrentValue().getClass();
        Field declaredField = ReflectionUtils.getDeclaredField(c,jsonParser.getCurrentName());
        Class<E> type = (Class<E>) declaredField.getType();
        if (NullUtils.isNotEmptyString(jsonParser.getValueAsString())){
            return (E) EnumCodeUtil.convert(type, jsonParser.getValueAsString());
        }else{
            return null;
        }
    }
}

EnumTypeHandler

作用基于mybatis框架实现对实现了EnumService的枚举进行数据库和服务器之间的序列化和反序列化
public class EnumTypeHandler<E extends Enum<E> & EnumCodeService> extends BaseTypeHandler<EnumCodeService> {

    private Class<E> type;

    public EnumTypeHandler(){

    }

    public EnumTypeHandler(Class<E> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        } else {
            this.type = type;
        }
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, EnumCodeService enumCode, JdbcType jdbcType) throws SQLException {
        preparedStatement.setInt(i, enumCode.getCode());
    }

    @Override
    public EnumCodeService getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return EnumCodeUtil.manageCode(type, resultSet.getInt(s));
    }

    @Override
    public EnumCodeService getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return EnumCodeUtil.manageCode(type, resultSet.getInt(i));
    }

    @Override
    public EnumCodeService getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return EnumCodeUtil.manageCode(type, callableStatement.getInt(i));
    }
}