枚举烦恼风
java枚举是个好动西,但是创建它往往非常麻烦,需要去翻译,复制,写方法;
BUT,TODAY,EVERYTHING HAS CHANGED, 鉴于之前建立了太多的JAVA枚举类让我防不胜防,我决定写一个静态类来创建自己需要的枚举类型,别的不说上代码,建立枚举只要几秒钟。
package com.beiming.xxx.xxx.test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.github.pagehelper.util.StringUtil;
import com.qcloud.Utilities.Json.JSONArray;
import lombok.experimental.var;
/**
* @author 使用GOOGLE翻译,快速创建枚举类代码
*
*/
public class Translator {
private static final Map<String, String> LANGUAGE_MAP = new HashMap();
/**
* 枚举类代码结尾部分,这是固定的 可以自己修改
*/
private static final String CLASS_END = "\r\n\r\nprivate String value;\r\n" + " private Integer order;\r\n" + " \r\n"
+ " private PreventIntensificationEnum(String value, Integer order) {\r\n" + " this.value = value;\r\n" + " this.order = order;\r\n"
+ " }\r\n" + "\r\n" + " public String getValue() {\r\n" + " return value;\r\n" + " }\r\n" + " \r\n" + " public Integer getOrder() {\r\n"
+ " return order;\r\n" + " }\r\n" + "}";
static {
init();
}
/**
* 初始化语言类
*/
private static void init() {
LANGUAGE_MAP.put("auto", "Automatic");
LANGUAGE_MAP.put("af", "Afrikaans");
LANGUAGE_MAP.put("sq", "Albanian");
LANGUAGE_MAP.put("am", "Amharic");
LANGUAGE_MAP.put("ar", "Arabic");
LANGUAGE_MAP.put("hy", "Armenian");
LANGUAGE_MAP.put("az", "Azerbaijani");
LANGUAGE_MAP.put("eu", "Basque");
LANGUAGE_MAP.put("be", "Belarusian");
LANGUAGE_MAP.put("bn", "Bengali");
LANGUAGE_MAP.put("bs", "Bosnian");
LANGUAGE_MAP.put("bg", "Bulgarian");
LANGUAGE_MAP.put("ca", "Catalan");
LANGUAGE_MAP.put("ceb", "Cebuano");
LANGUAGE_MAP.put("ny", "Chichewa");
LANGUAGE_MAP.put("zh_cn", "Chinese Simplified");
LANGUAGE_MAP.put("zh_tw", "Chinese Traditional");
LANGUAGE_MAP.put("co", "Corsican");
LANGUAGE_MAP.put("hr", "Croatian");
LANGUAGE_MAP.put("cs", "Czech");
LANGUAGE_MAP.put("da", "Danish");
LANGUAGE_MAP.put("nl", "Dutch");
LANGUAGE_MAP.put("en", "English");
LANGUAGE_MAP.put("eo", "Esperanto");
LANGUAGE_MAP.put("et", "Estonian");
LANGUAGE_MAP.put("tl", "Filipino");
LANGUAGE_MAP.put("fi", "Finnish");
LANGUAGE_MAP.put("fr", "French");
LANGUAGE_MAP.put("fy", "Frisian");
LANGUAGE_MAP.put("gl", "Galician");
LANGUAGE_MAP.put("ka", "Georgian");
LANGUAGE_MAP.put("de", "German");
LANGUAGE_MAP.put("el", "Greek");
LANGUAGE_MAP.put("gu", "Gujarati");
LANGUAGE_MAP.put("ht", "Haitian Creole");
LANGUAGE_MAP.put("ha", "Hausa");
LANGUAGE_MAP.put("haw", "Hawaiian");
LANGUAGE_MAP.put("iw", "Hebrew");
LANGUAGE_MAP.put("hi", "Hindi");
LANGUAGE_MAP.put("hmn", "Hmong");
LANGUAGE_MAP.put("hu", "Hungarian");
LANGUAGE_MAP.put("is", "Icelandic");
LANGUAGE_MAP.put("ig", "Igbo");
LANGUAGE_MAP.put("id", "Indonesian");
LANGUAGE_MAP.put("ga", "Irish");
LANGUAGE_MAP.put("it", "Italian");
LANGUAGE_MAP.put("ja", "Japanese");
LANGUAGE_MAP.put("jw", "Javanese");
LANGUAGE_MAP.put("kn", "Kannada");
LANGUAGE_MAP.put("kk", "Kazakh");
LANGUAGE_MAP.put("km", "Khmer");
LANGUAGE_MAP.put("ko", "Korean");
LANGUAGE_MAP.put("ku", "Kurdish (Kurmanji)");
LANGUAGE_MAP.put("ky", "Kyrgyz");
LANGUAGE_MAP.put("lo", "Lao");
LANGUAGE_MAP.put("la", "Latin");
LANGUAGE_MAP.put("lv", "Latvian");
LANGUAGE_MAP.put("lt", "Lithuanian");
LANGUAGE_MAP.put("lb", "Luxembourgish");
LANGUAGE_MAP.put("mk", "Macedonian");
LANGUAGE_MAP.put("mg", "Malagasy");
LANGUAGE_MAP.put("ms", "Malay");
LANGUAGE_MAP.put("ml", "Malayalam");
LANGUAGE_MAP.put("mt", "Maltese");
LANGUAGE_MAP.put("mi", "Maori");
LANGUAGE_MAP.put("mr", "Marathi");
LANGUAGE_MAP.put("mn", "Mongolian");
LANGUAGE_MAP.put("my", "Myanmar (Burmese)");
LANGUAGE_MAP.put("ne", "Nepali");
LANGUAGE_MAP.put("no", "Norwegian");
LANGUAGE_MAP.put("ps", "Pashto");
LANGUAGE_MAP.put("fa", "Persian");
LANGUAGE_MAP.put("pl", "Polish");
LANGUAGE_MAP.put("pt", "Portuguese");
LANGUAGE_MAP.put("ma", "Punjabi");
LANGUAGE_MAP.put("ro", "Romanian");
LANGUAGE_MAP.put("ru", "Russian");
LANGUAGE_MAP.put("sm", "Samoan");
LANGUAGE_MAP.put("gd", "Scots Gaelic");
LANGUAGE_MAP.put("sr", "Serbian");
LANGUAGE_MAP.put("st", "Sesotho");
LANGUAGE_MAP.put("sn", "Shona");
LANGUAGE_MAP.put("sd", "Sindhi");
LANGUAGE_MAP.put("si", "Sinhala");
LANGUAGE_MAP.put("sk", "Slovak");
LANGUAGE_MAP.put("sl", "Slovenian");
LANGUAGE_MAP.put("so", "Somali");
LANGUAGE_MAP.put("es", "Spanish");
LANGUAGE_MAP.put("su", "Sundanese");
LANGUAGE_MAP.put("sw", "Swahili");
LANGUAGE_MAP.put("sv", "Swedish");
LANGUAGE_MAP.put("tg", "Tajik");
LANGUAGE_MAP.put("ta", "Tamil");
LANGUAGE_MAP.put("te", "Telugu");
LANGUAGE_MAP.put("th", "Thai");
LANGUAGE_MAP.put("tr", "Turkish");
LANGUAGE_MAP.put("uk", "Ukrainian");
LANGUAGE_MAP.put("ur", "Urdu");
LANGUAGE_MAP.put("uz", "Uzbek");
LANGUAGE_MAP.put("vi", "Vietnamese");
LANGUAGE_MAP.put("cy", "Welsh");
LANGUAGE_MAP.put("xh", "Xhosa");
LANGUAGE_MAP.put("yi", "Yiddish");
LANGUAGE_MAP.put("yo", "Yoruba");
LANGUAGE_MAP.put("zu", "Zulu");
}
public static String translate(String langFrom, String langTo, String word) throws Exception {
String url = "https://translate.googleapis.com/translate_a/single?" + "client=gtx" + "&sl=" + langFrom + "&tl=" + langTo + "&dt=t&q="
+ URLEncoder.encode(word, "UTF-8");
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return parseResult(response.toString());
}
private static String parseResult(String inputJson) throws Exception {
JSONArray jsonArray = new JSONArray(inputJson);
JSONArray jsonArray2 = (JSONArray) jsonArray.get(0);
// JSONArray jsonArray3 = (JSONArray) jsonArray2.get(0);
String result = "";
for (var i = 0; i < jsonArray2.length(); i++) {
result += ((JSONArray) jsonArray2.get(i)).get(0).toString();
}
return result;
}
/**
* 中问翻译为英文
*
* @param chinese
* @return
* @throws Exception
*/
public static String translateToEnglish(String chinese) {
String english = "";
try {
english = translate("zh-CN", "en", chinese);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return english;
}
/**
* 处理中文枚举转换为英文大写翻译,然后建立枚举类
*
* @param enumClassName // 你想要建立的枚举类名
* @param chinese // 枚举列值中文说明
*
*
* 简单纠纷 一般纠纷 重大纠纷 疑难纠纷
*
* @param order 枚举排序/可选/不传自动创建排序从1开始 01 02 03 04
* @param desc 枚举描述
*/
public static void quickCreateEnum(String enumClassName, String chinese, String order, String desc) {
String classDesc = "/**\r\n" + " * Desc:YOURDESC\r\n" + " * @author JACKR\r\n" + " *\r\n" + " */ \r\n";
classDesc = classDesc.replace("YOURDESC", desc);
String header = classDesc + "public enum " + enumClassName + " {\r\n";
chinese = chinese.replace("\r", "").trim(); // 去掉中文换行
String english = Translator.translateToEnglish(chinese);
// 获取翻译后的英文并且转为大写加下划线
String translatedStr = english.replace(" ", "_").toUpperCase();
List<String> listEnglish = changeStrToList(translatedStr);
List<String> listChinese = changeStrToList(chinese);
// 处理排序
if (!StringUtil.isEmpty(order)) {
order = order.replace("\r", "").trim(); // 去掉排序换行
}
List<String> listOrder = initOrder(listChinese.size());
if (!StringUtil.isEmpty(order)) {
listOrder = changeStrToList(order);
}
String result = "";
for (int i = 0; i < listChinese.size(); i++) {
result += listEnglish.get(i) + "(" + "\"" + listChinese.get(i) + "\", " + listOrder.get(i) + "), " + "\n";
}
result = result.substring(0, result.length() - 3);
result += ";";
String finalClass = header + result + CLASS_END;
System.out.println(finalClass);
}
public static List<String> initOrder(int size) {
List<String> list = new ArrayList<>();
for (int i = 1; i < size + 1; i++) {
list.add(String.valueOf(i));
}
return list;
}
/**
* 获取List用\n分割
*/
public static List<String> changeStrToList(String chinese) {
String[] arr = chinese.split("\n");
List<String> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
if (arr[i].startsWith("0")) {
arr[i] = arr[i].replace("0", "");
}
list.add(arr[i]);
}
return list;
}
public static void main(String[] args) {
String enumClassName = "HelloEnum";
String classDesc = "这是我要新建的枚举类";
String chineseListStr = "简单纠纷\r\n" + "一般纠纷\r\n" + "重大纠纷\r\n" + "疑难纠纷\r\n" + "";
String orderListStr = "01\r\n" + "02\r\n" + "03\r\n" + "04\r\n" + "";
quickCreateEnum(enumClassName, chineseListStr, null, classDesc);
}
}
运行main方法,会得到如下结果
/**
* Desc:这是我要新建的枚举类
* @author JACKR
*
*/
public enum HelloEnum {
SIMPLE_DISPUTE("简单纠纷", 1),
GENERAL_DISPUTE("一般纠纷", 2),
MAJOR_DISPUTE("重大纠纷", 3),
DIFFICULT_DISPUTE("疑难纠纷", 4);
private String value;
private Integer order;
private PreventIntensificationEnum(String value, Integer order) {
this.value = value;
this.order = order;
}
public String getValue() {
return value;
}
public Integer getOrder() {
return order;
}
}
quickCreateEnum方法可以快速创建枚举类代码,只需要三秒
扩充部分
但是光是创建枚举会很累,前端对接也不知道该传什么值,有什么好的解决办法呢,这时候会想到反射,在项目启动的时候初始化枚举到MAP中,前端通过接口传递类型直接调用,则可查看对应的枚举列表。
反射枚举类
package com.beiming.xxx.xxx.common.utils;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* 获取指定包下面所有类方法
*
* @author JACKR
*
*/
public class ClazzUtil {
/**
* 从包package中获取所有的Class
*
* @param pack
* @return
*/
public static Set<Class<?>> getClasses(String pack) {
// 第一个class类的集合
Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
// 是否循环迭代
boolean recursive = true;
// 获取包的名字 并进行替换
String packageName = pack;
String packageDirName = packageName.replace('.', '/');
// 定义一个枚举的集合 并进行循环来处理这个目录下的things
Enumeration<URL> dirs;
try {
dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
// 循环迭代下去
while (dirs.hasMoreElements()) {
// 获取下一个元素
URL url = dirs.nextElement();
// 得到协议的名称
String protocol = url.getProtocol();
// 如果是以文件的形式保存在服务器上
if ("file".equals(protocol)) {
// System.err.println("file类型的扫描");
// 获取包的物理路径
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
// 以文件的方式扫描整个包下的文件 并添加到集合中
findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes);
} else if ("jar".equals(protocol)) {
// 如果是jar包文件
// 定义一个JarFile
// System.err.println("jar类型的扫描");
JarFile jar;
// 获取jar
jar = ((JarURLConnection) url.openConnection()).getJarFile();
// 从此jar包 得到一个枚举类
Enumeration<JarEntry> entries = jar.entries();
// 同样的进行循环迭代
while (entries.hasMoreElements()) {
processClass(entries, packageDirName, packageName, recursive, classes);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return classes;
}
/**
* Desc: 获取CLASS.
*
* @param entries
* @param packageDirName
* @param packageName
* @param recursive
* @param classes
*/
public static void processClass(Enumeration<JarEntry> entries, String packageDirName, String packageName, Boolean recursive,
Set<Class<?>> classes) {
// 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
JarEntry entry = entries.nextElement();
String name = entry.getName();
// 如果是以/开头的
if (name.charAt(0) == '/') {
// 获取后面的字符串
name = name.substring(1);
}
// 如果前半部分和定义的包名相同
if (name.startsWith(packageDirName)) {
int idx = name.lastIndexOf('/');
// 如果以"/"结尾 是一个包
if (idx != -1) {
// 获取包名 把"/"替换成"."
packageName = name.substring(0, idx).replace('/', '.');
}
// 如果可以迭代下去 并且是一个包
Boolean flag = (idx != -1) || recursive;
if (flag && name.endsWith(".class") && !entry.isDirectory()) {
// 如果是一个.class文件 而且不是目录
// 去掉后面的".class" 获取真正的类名
String className = name.substring(packageName.length() + 1, name.length() - 6);
try {
// 添加到classes
classes.add(Class.forName(packageName + '.' + className));
} catch (ClassNotFoundException e) {
// log.error("添加用户自定义视图类错误找不到此类的.class文件");
e.printStackTrace();
}
}
}
}
/**
* 以文件的形式来获取包下的所有Class
*
* @param packageName
* @param packagePath
* @param recursive
* @param classes
*/
public static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive, Set<Class<?>> classes) {
// 获取此包的目录 建立一个File
File dir = new File(packagePath);
// 如果不存在或者 也不是目录就直接返回
if (!dir.exists() || !dir.isDirectory()) {
// log.warn("用户定义包名 " + packageName + " 下没有任何文件");
return;
}
// 如果存在 就获取包下的所有文件 包括目录
File[] dirfiles = dir.listFiles(new FileFilter() {
// 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
public boolean accept(File file) {
return (recursive && file.isDirectory()) || (file.getName().endsWith(".class"));
}
});
// 循环所有文件
for (File file : dirfiles) {
// 如果是目录 则继续扫描
if (file.isDirectory()) {
findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, classes);
} else {
// 如果是java类文件 去掉后面的.class 只留下类名
String className = file.getName().substring(0, file.getName().length() - 6);
try {
// 添加到集合中去
// classes.add(Class.forName(packageName + '.' +
// className));
// 经过回复同学的提醒,这里用forName有一些不好,会触发static方法,没有使用classLoader的load干净
classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className));
} catch (ClassNotFoundException e) {
// log.error("添加用户自定义视图类错误 找不到此类的.class文件");
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
}
}
初始化枚举数据UTIL类
package com.beiming.nonlitigation.business.common.utils;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import com.beiming.nonlitigation.business.common.commondto.TypeResponseDTO;
/**
* 获取枚举相关信息的静态类
* @author JACKR
*
*/
public class EnumsTypeUtil {
public static final String DEFAULT_PACKAGE = "com.beiming.nonlitigation.business.common.enums";
/**
* 存放类型的枚举数据map
*/
public static HashMap<String, List<TypeResponseDTO>> typeListMap = new HashMap<>();
static {
initAllEnumMap(); // 初始化枚举信息MAP
}
/**
* 枚举转map结合value作为map的key,description作为map的value 必须有order字段和对应getOrder方法
*
* @param enumT
* @param methodNames
* @return enum mapcolloction
*/
public static <T> Map<String, TypeResponseDTO> enumToMap(Class<T> enumT, String... methodNames) {
Map<String, TypeResponseDTO> enummap = new HashMap<String, TypeResponseDTO>();
// 不是枚举类
if (!enumT.isEnum()) {
return enummap;
}
T[] enums = enumT.getEnumConstants();
if (enums == null || enums.length <= 0) {
return enummap;
}
int count = methodNames.length;
/** 默认接口value方法 */
String valueMathod = "getValue";
/** 默认接口typeName方法 */
String desMathod = "getTypeName";
/** 获取排序的方法 */
String orderMethod = "getOrder";
/** 扩展方法 */
if (count >= 1 && !"".equals(methodNames[0])) {
valueMathod = methodNames[0];
}
if (count == 2 && !"".equals(methodNames[1])) {
desMathod = methodNames[1];
}
for (int i = 0, len = enums.length; i < len; i++) {
T tobj = enums[i];
try {
/** 获取value值 */
Object resultValue = getMethodValue(valueMathod, tobj);
if ("".equals(resultValue)) {
continue;
}
/** 获取typeName描述值 */
Object resultDes = getMethodValue(desMathod, tobj);
/** 如果描述不存在获取属性值 */
if ("".equals(resultDes)) {
resultDes = tobj;
}
/** 获取顺序 */
Object orderDes = getMethodValue(orderMethod, tobj);
Integer order = 0;
/** 获取顺序 */
if (!"".equals(orderDes)) {
order = Integer.parseInt(orderDes + "");
}
TypeResponseDTO dto = new TypeResponseDTO(resultValue + "", resultDes + "", order);
enummap.put(resultDes + "", dto);
} catch (Exception e) {
e.printStackTrace();
}
}
return enummap;
}
/**
* 根据反射,通过方法名称获取方法值,忽略大小写的
*
* @param methodName
* @param obj
* @param args
* @return return value
*/
private static <T> Object getMethodValue(String methodName, T obj, Object... args) {
Object resut = "";
try {
/********************************* start *****************************************/
/** 获取方法数组,这里只要共有的方法 */
Method[] methods = obj.getClass().getMethods();
if (methods.length <= 0) {
return resut;
}
Method method = null;
for (int i = 0, len = methods.length; i < len; i++) {
/** 忽略大小写取方法 */
if (methods[i].getName().equalsIgnoreCase(methodName)) {
/** 如果存在,则取出正确的方法名称 */
methodName = methods[i].getName();
method = methods[i];
break;
}
}
/*************************** end ***********************************************/
if (method == null) {
return resut;
}
/** 方法执行 */
resut = method.invoke(obj, args);
if (resut == null) {
resut = "";
}
/** 返回结果 */
return resut;
} catch (Exception e) {
e.printStackTrace();
}
return resut;
}
/**
* 通过value值获取对应的描述信息
*
* @param value
* @param enumT
* @param methodNames
* @return enum description
*/
public static <T> Object getEnumDescriotionByValue(Object value, Class<T> enumT, String... methodNames) {
/** 不是枚举则返回"" */
if (!enumT.isEnum()) {
return "";
}
/** 获取枚举的所有枚举属性,似乎这几句也没啥用,一般既然用枚举,就一定会添加枚举属性 */
T[] enums = enumT.getEnumConstants();
if (enums == null || enums.length <= 0) {
return "";
}
int count = methodNames.length;
/** 默认获取枚举value方法,与接口方法一致 */
String valueMathod = "getValue";
/** 默认获取枚举getTypeName方法 */
String desMathod = "getTypeName";
if (count >= 1 && !"".equals(methodNames[0])) {
valueMathod = methodNames[0];
}
if (count == 2 && !"".equals(methodNames[1])) {
desMathod = methodNames[1];
}
for (int i = 0, len = enums.length; i < len; i++) {
T t = enums[i];
try {
/** 获取枚举对象value */
Object resultValue = getMethodValue(valueMathod, t);
if (resultValue.toString().equals(value + "")) {
/** 存在则返回对应描述 */
Object resultDes = getMethodValue(desMathod, t);
return resultDes;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return "";
}
/**
* 通过枚举value或者自定义值及方法获取枚举属性值
*
* @param value
* @param enumT
* @param methodNames
* @return enum key
*/
public static <T> String getEnumKeyByValue(Object value, Class<T> enumT, String... methodNames) {
if (!enumT.isEnum()) {
return "";
}
T[] enums = enumT.getEnumConstants();
if (enums == null || enums.length <= 0) {
return "";
}
int count = methodNames.length;
/** 默认方法 */
String valueMathod = "getValue";
/** 独立方法 */
if (count >= 1 && !"".equals(methodNames[0])) {
valueMathod = methodNames[0];
}
for (int i = 0, len = enums.length; i < len; i++) {
T tobj = enums[i];
try {
Object resultValue = getMethodValue(valueMathod, tobj);
/** 存在则返回对应值 */
if (resultValue != null && resultValue.toString().equals(value + "")) {
return tobj + "";
}
} catch (Exception e) {
e.printStackTrace();
}
}
return "";
}
/**
* 转换成List
*
* @param enumT
* @param methodNames
* @return List<String>
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public static <T> List<String> getEnumToList(Class<T> enumT, String... methodNames) {
Map<String, TypeResponseDTO> map = enumToMap(enumT);
List<String> result = new ArrayList(map.values());
return result;
}
/**
* Desc: 通过枚举类型获取枚举list.
*
* @param enumsType
* @return
*/
public static List<TypeResponseDTO> getTypeList(String enumsType) {
String enumName = DEFAULT_PACKAGE + "." + enumsType;
System.out.println("请求获取枚:" + enumName);
// 直接从MAP中获取
if (typeListMap.containsKey(enumName)) {
System.out.println(typeListMap.keySet());
return typeListMap.get(enumName);
} else {
return new ArrayList<TypeResponseDTO>();
}
}
/**
* Desc:将指定包名下的所有枚举类初始化成MAP .
*
*/
public static void initAllEnumMap() {
// 通过包名获取所有clazz对象
Set<Class<?>> clazzSet = ClazzUtil.getClasses(DEFAULT_PACKAGE);
clazzSet.stream().forEach(item -> {
List<TypeResponseDTO> list = new ArrayList<>();
Map<String, TypeResponseDTO> map = enumToMap(item);
for (TypeResponseDTO dto : map.values()) {
list.add(dto);
}
// 排序 默认升序
List<TypeResponseDTO> sortedList = list.stream().sorted((o1, o2) -> o1.getOrder() - o2.getOrder()).collect(Collectors.toList());
if (list.size() > 0) {
typeListMap.put(item.getName(), sortedList);
}
});
}
public static void main(String[] args) {
initAllEnumMap();
System.out.println(typeListMap);
}
}
getEnumTypeList返回的DTO对象
package com.beiming.nonlitigation.business.common.commondto;
import java.io.Serializable;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class TypeResponseDTO implements Serializable {
@ApiModelProperty(value = "名字")
private String name;
@ApiModelProperty(value = "值")
private String value;
@ApiModelProperty(value = "顺序")
private Integer order;
}
service类中接口
@Override
public DubboResult getEnumTypeList(String type) {
List<TypeResponseDTO> list = EnumsTypeUtil.getTypeList(type);
return DubboResultBuilder.success((Serializable) list);
}
总结
这几个类就可以快速创建枚举,并且为前端提供了一个查询所有枚举的接口,提高了开发效率,后续会进一步优化,准备提供一个读取文件创建枚举类的方法,并且提供一个万能工具箱来创建需要创建的对象。