com.power.common.util.EnumUtil Maven / Gradle / Ivy
package com.power.common.util;
import com.power.common.model.EnumDictionary;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
/**
* @author yu 2019/12/7.
*/
public class EnumUtil {
/**
* get enum values
*
* @param clazz class
* @param codeField code field
* @param descField desc field
* @param subclass of EnumDictionary
* @return list
*/
public static List getEnumInformation(Class> clazz, String codeField, String descField) {
if (!clazz.isEnum()) {
throw new RuntimeException(clazz.getCanonicalName() + " is not an enum class.");
}
Class enumClass = (Class) clazz;
Enum[] objects = enumClass.getEnumConstants();
String valueMethodName = "get" + StringUtil.firstToUpperCase(codeField);
String descMethodName = "get" + StringUtil.firstToUpperCase(descField);
List enumDictionaryList = new ArrayList<>();
try {
Method valueMethod = clazz.getMethod(valueMethodName);
Method descMethod = clazz.getMethod(descMethodName);
for (Enum enumType : objects) {
Object val = valueMethod.invoke(enumType);
Object desc = descMethod.invoke(enumType);
EnumDictionary dataDict = new EnumDictionary();
String type = ClassUtil.getSimpleTypeName(val);
dataDict.setType(type);
dataDict.setDesc(String.valueOf(desc));
dataDict.setValue(String.valueOf(val));
String name = enumType.name();
int ordinal = enumType.ordinal();
dataDict.setName(name);
dataDict.setOrdinal(ordinal);
enumDictionaryList.add((T) dataDict);
}
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
return enumDictionaryList;
}
/**
* Get enum information
*
* @param clazz java class
* @return hash map
*/
public static Map>> getEnumInformation(Class> clazz) {
if (Objects.isNull(clazz)) {
throw new RuntimeException("Enum class can't be null.");
}
if (!clazz.isEnum()) {
throw new RuntimeException("It's not an enum class.");
}
Map>> enumTypeMap = new HashMap<>();
Class enumClass = (Class) clazz;
List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy