diff --git a/src/main/java/cn/zhangdeman/HashMapCache.java b/src/main/java/cn/zhangdeman/HashMapCache.java index a7ba6b9..cc5dd20 100644 --- a/src/main/java/cn/zhangdeman/HashMapCache.java +++ b/src/main/java/cn/zhangdeman/HashMapCache.java @@ -9,7 +9,9 @@ import org.springframework.core.annotation.AnnotationUtils; import org.springframework.util.ClassUtils; import java.io.File; +import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.util.*; @@ -43,9 +45,23 @@ public class HashMapCache implements ServletContextListener { continue; } // 实现了接口 + Map codeTable = new HashMap<>(); // 反射获取类实例 - ICustomExceptionAnnotation iCustomExceptionAnnotation = (ICustomExceptionAnnotation) (classInstance.getDeclaredConstructor().newInstance()); - Map codeTable = iCustomExceptionAnnotation.getCodeTable(); + if (!classInstance.isEnum()) { + // 不是枚举类 + 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 : 获取分类注解 for (Map.Entry entry: codeTable.entrySet()) { getInstance().put(entry.getKey(), entry.getValue()); @@ -125,7 +141,7 @@ public class HashMapCache implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { - System.out.println("包内自动触发初始化" + new Date()); + System.out.println("[start]自动执行异常配置注入" + new Date()); try { this.loadCustomException(); } catch (ClassNotFoundException e) { @@ -139,6 +155,7 @@ public class HashMapCache implements ServletContextListener { } catch (InstantiationException e) { throw new RuntimeException(e); } + System.out.println("[finish]自动执行异常配置注入" + new Date()); } @Override diff --git a/src/main/java/cn/zhangdeman/IExceptionConfig.java b/src/main/java/cn/zhangdeman/IExceptionConfig.java new file mode 100644 index 0000000..f01e779 --- /dev/null +++ b/src/main/java/cn/zhangdeman/IExceptionConfig.java @@ -0,0 +1,6 @@ +package cn.zhangdeman; + +public interface IExceptionConfig { + String getCode(); + String getMessage(); +}