完成反射获取全部的枚举值, 细节待优化

This commit is contained in:
白茶清欢 2025-06-03 17:28:35 +08:00
parent 61402bfac7
commit e23e7969e1
2 changed files with 26 additions and 3 deletions

View File

@ -9,7 +9,9 @@ import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.ClassUtils; import org.springframework.util.ClassUtils;
import java.io.File; import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*; import java.util.*;
@ -43,9 +45,23 @@ public class HashMapCache implements ServletContextListener {
continue; continue;
} }
// 实现了接口 // 实现了接口
Map<String, String> codeTable = new HashMap<>();
// 反射获取类实例 // 反射获取类实例
ICustomExceptionAnnotation iCustomExceptionAnnotation = (ICustomExceptionAnnotation) (classInstance.getDeclaredConstructor().newInstance()); if (!classInstance.isEnum()) {
Map<String, String> codeTable = iCustomExceptionAnnotation.getCodeTable(); // 不是枚举类
Constructor<?> constructor = classInstance.getDeclaredConstructor();
constructor.setAccessible(true);
ICustomExceptionAnnotation iCustomExceptionAnnotation = (ICustomExceptionAnnotation) (constructor.newInstance());
codeTable = iCustomExceptionAnnotation.getCodeTable();
} else {
// 是枚举类
Method method = classInstance.getMethod("values");
Object[] objectList = (Object[]) method.invoke(null);
for (Object itemEnumObject: objectList) {
codeTable.put(((IExceptionConfig)itemEnumObject).getCode(), ((IExceptionConfig)itemEnumObject).getMessage());
}
}
// TODO : 获取分类注解 // TODO : 获取分类注解
for (Map.Entry<String, String> entry: codeTable.entrySet()) { for (Map.Entry<String, String> entry: codeTable.entrySet()) {
getInstance().put(entry.getKey(), entry.getValue()); getInstance().put(entry.getKey(), entry.getValue());
@ -125,7 +141,7 @@ public class HashMapCache implements ServletContextListener {
@Override @Override
public void contextInitialized(ServletContextEvent sce) { public void contextInitialized(ServletContextEvent sce) {
System.out.println("包内自动触发初始化" + new Date()); System.out.println("[start]自动执行异常配置注入" + new Date());
try { try {
this.loadCustomException(); this.loadCustomException();
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
@ -139,6 +155,7 @@ public class HashMapCache implements ServletContextListener {
} catch (InstantiationException e) { } catch (InstantiationException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
System.out.println("[finish]自动执行异常配置注入" + new Date());
} }
@Override @Override

View File

@ -0,0 +1,6 @@
package cn.zhangdeman;
public interface IExceptionConfig {
String getCode();
String getMessage();
}