同步数据库数据到枚举类

编程

最近需要优化下枚举,特地网上找了很多方法,尝试加载数据库的方式,找了很久,终于找到方法

原文链接: https://jingyan.baidu.com/article/3c343ff7baea5b0d377963f3.html

这里做下记录,免得以后需要又找不到

备注:枚举有多个字段,只需在   makeEnum(enumType, name, values.size(), new Class[]{Integer.class}, new Object[]{value});  的数组中添加对应的字段类型,以及对应的值即可,需要启动加载的话,添加 @postconstruct 就行了

 

/**

* @author lin

* @create 2020/7/30

*/

public enum EnumDemo {

NON(-1, "123");

private Integer value;

private String remark;

EnumDemo(Integer value, String remark){

this.value = value;

this.remark = remark;

}

public Integer getValue() {

return value;

}

public void setValue(Integer value) {

this.value = value;

}

public String getRemark() {

return remark;

}

public void setRemark(String remark) {

this.remark = remark;

}

@Override

public String toString() {

return "EnumDemo{" +

"value=" + value +

", remark="" + remark + """ +

"}";

}

}

 

import sun.reflect.ConstructorAccessor;

import sun.reflect.FieldAccessor;

import sun.reflect.ReflectionFactory;

import java.lang.reflect.AccessibleObject;

import java.lang.reflect.Array;

import java.lang.reflect.Constructor;

import java.lang.reflect.Field;

import java.lang.reflect.Modifier;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

/**

* @author lin

* @create 2020/7/30

*/

public class EnumService {

public static void main(String[] args) {

//1、数据库查询

// List<Map<String, Object>> dataList = daoc.queryData(...);

List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();

dataList.add(new HashMap<String, Object>());

dataList.add(new HashMap<String, Object>());

dataList.add(new HashMap<String, Object>());

dataList.add(new HashMap<String, Object>());

dataList.get(0).put("KEY", "MON");

dataList.get(0).put("VALUE", 1);

dataList.get(0).put("REMARK", "111");

dataList.get(1).put("KEY", "TUE");

dataList.get(1).put("VALUE", 2);

dataList.get(1).put("REMARK", "222");

dataList.get(2).put("KEY", "WED");

dataList.get(2).put("VALUE", 3);

dataList.get(2).put("REMARK", "333");

dataList.get(3).put("KEY", "THU");

dataList.get(3).put("VALUE", 4);

dataList.get(3).put("REMARK", "444");

//2、添加枚举

for (Map<String, Object> map : dataList) {

addEnum(EnumDemo.class, map.get("KEY").toString(), map.get("VALUE"), map.get("REMARK"));

}

//3、打印验证

for (EnumDemo e : EnumDemo.values()) {

System.out.println(e.toString());

}

}

@SuppressWarnings("unchecked")

public static <T extends Enum<?>> void addEnum(Class<T> enumType, String name, Object value, Object remark) {

// 0. Sanity checks

if (!Enum.class.isAssignableFrom(enumType)) {

throw new RuntimeException("class " + enumType + " is not an instance of Enum");

}

Field valuesField = null;

Field[] fields = EnumDemo.class.getDeclaredFields();

for (Field field : fields) {

if (field.getName().contains("$VALUES")) {

valuesField = field;

break;

}

}

AccessibleObject.setAccessible(new Field[]{valuesField}, true);

try {

// 2. Copy it

T[] previousValues = (T[]) valuesField.get(enumType);

List<T> values = new ArrayList<T>(Arrays.asList(previousValues));

// 3. build new enum

//TODO 多个字段往数组添加对应的类型以及值就可以 T newValue = (T) makeEnum(enumType, name, values.size(), new Class[]{Integer.class}, new Object[]{value});

T newValue = (T) makeEnum(enumType, name, values.size(), new Class[]{Integer.class, String.class}, new Object[]{value, remark});

// 4. add new value

values.add(newValue);

Object object = values.toArray((EnumDemo[]) Array.newInstance(EnumDemo.class, 0));

// 5. Set new values field

setFailsafeFieldValue(valuesField, null, object);

// 6. Clean enum cache

cleanEnumCache(EnumDemo.class);

} catch (Exception e) {

e.printStackTrace();

throw new RuntimeException(e.getMessage(), e);

}

}

private static void cleanEnumCache(Class<?> enumClass) throws NoSuchFieldException, IllegalAccessException {

blankField(enumClass, "enumConstantDirectory"); // Sun (Oracle?!?) JDK 1.5/6

blankField(enumClass, "enumConstants"); // IBM JDK

}

private static void blankField(Class<?> enumClass, String fieldName) throws NoSuchFieldException, IllegalAccessException {

for (Field field : Class.class.getDeclaredFields()) {

if (field.getName().contains(fieldName)) {

AccessibleObject.setAccessible(new Field[]{field}, true);

setFailsafeFieldValue(field, enumClass, null);

break;

}

}

}

private static void setFailsafeFieldValue(Field field, Object target, Object value) throws NoSuchFieldException, IllegalAccessException {

// let"s make the field accessible

field.setAccessible(true);

// next we change the modifier in the Field instance to

// not be final anymore, thus tricking reflection into

// letting us modify the static final field

Field modifiersField = Field.class.getDeclaredField("modifiers");

modifiersField.setAccessible(true);

int modifiers = modifiersField.getInt(field);

// blank out the final bit in the modifiers int

modifiers &= ~Modifier.FINAL;

modifiersField.setInt(field, modifiers);

FieldAccessor fa = ReflectionFactory.getReflectionFactory().newFieldAccessor(field, false);

fa.set(target, value);

}

private static Object makeEnum(Class<?> enumClass, String value, int ordinal, Class<?>[] additionalTypes,

Object[] additionalValues) throws Exception {

Object[] parms = new Object[additionalValues.length + 2];

parms[0] = value;

parms[1] = Integer.valueOf(ordinal);

System.arraycopy(additionalValues, 0, parms, 2, additionalValues.length);

return enumClass.cast(getConstructorAccessor(enumClass, additionalTypes).newInstance(parms));

}

private static ConstructorAccessor getConstructorAccessor(Class<?> enumClass, Class<?>[] additionalParameterTypes)

throws NoSuchMethodException {

Class<?>[] parameterTypes = new Class[additionalParameterTypes.length + 2];

parameterTypes[0] = String.class;

parameterTypes[1] = int.class;

System.arraycopy(additionalParameterTypes, 0, parameterTypes, 2, additionalParameterTypes.length);

Constructor<?> constructor = enumClass.getDeclaredConstructor(parameterTypes);

return ReflectionFactory.getReflectionFactory().newConstructorAccessor(constructor);

}

}

 

 

以上是 同步数据库数据到枚举类 的全部内容, 来源链接: utcz.com/z/518909.html

回到顶部