美文网首页
工具类 java枚举类作数据字典,枚举的key和message扫

工具类 java枚举类作数据字典,枚举的key和message扫

作者: LAMYMAY | 来源:发表于2022-01-18 16:01 被阅读0次

    把枚举转换成List<key-value>示意图:

    image.png

    核心代码


    image.png
    说明:
    1 我这边定义的枚举类都是实现了统一接口(统一枚举行为)
    2 用到一个工具类,知道一个包名称获取包下的全部类
    
    

    源码片段:

    /**
    * 枚举约束接口
     * @author may
     * @since 2021
     */
    public interface EnumStringInterface {
    
        /**
         * @return 枚举的标示
         */
        String getKey();
    
        /**
         * @return 枚举描述信息
         */
        String getMessage();
    
    
    }
    
    
    public enum LevelEnum implements EnumStringInterface {
    
        BUILDING("building", "幢"),
        UNIT("unit", "单元"),
        FLOOR("floor", "层")
    ;
    }
    

    工具类

    
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.io.File;
    import java.io.FileFilter;
    import java.net.JarURLConnection;
    import java.net.URL;
    import java.util.Enumeration;
    import java.util.HashSet;
    import java.util.Set;
    import java.util.jar.JarEntry;
    import java.util.jar.JarFile;
    
    /**
     * 类操作工具类
     *
     * @author may
     * @since 2021.08.17 11:58 上午
     */
    public final class ClassUtil {
    
        private static final Logger LOGGER = LoggerFactory.getLogger(ClassUtil.class);
    
        /**
         * 获取类加载器
         */
        public static ClassLoader getClassLoader() {
            return Thread.currentThread().getContextClassLoader();
        }
    
        /**
         * 加载类
         */
        public static Class<?> loadClass(String className, boolean isInitialized) {
            Class<?> cls;
            try {
                cls = Class.forName(className, isInitialized, getClassLoader());
            } catch (ClassNotFoundException e) {
                LOGGER.error("load class failure", e);
                throw new RuntimeException(e);
            }
            return cls;
        }
    
        /**
         * 加载类(默认将初始化类)
         */
        public static Class<?> loadClass(String className) {
            return loadClass(className, true);
        }
    
        /**
         * 获取指定包名下的所有类
         */
        public static Set<Class<?>> getClassSet(String packageName) {
            Set<Class<?>> classSet = new HashSet<Class<?>>();
            try {
                Enumeration<URL> urls = getClassLoader().getResources(packageName.replace(".", "/"));
                while (urls.hasMoreElements()) {
                    URL url = urls.nextElement();
                    if (url != null) {
                        String protocol = url.getProtocol();
                        if (protocol.equals("file")) {
                            String packagePath = url.getPath().replaceAll("%20", " ");
                            addClass(classSet, packagePath, packageName);
                        } else if (protocol.equals("jar")) {
                            JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
                            if (jarURLConnection != null) {
                                JarFile jarFile = jarURLConnection.getJarFile();
                                if (jarFile != null) {
                                    Enumeration<JarEntry> jarEntries = jarFile.entries();
                                    while (jarEntries.hasMoreElements()) {
                                        JarEntry jarEntry = jarEntries.nextElement();
                                        String jarEntryName = jarEntry.getName();
                                        if (jarEntryName.endsWith(".class")) {
                                            String className = jarEntryName.substring(0, jarEntryName.lastIndexOf(".")).replaceAll("/", ".");
                                            doAddClass(classSet, className);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                LOGGER.error("get class set failure", e);
                throw new RuntimeException(e);
            }
            return classSet;
        }
    
        private static void addClass(Set<Class<?>> classSet, String packagePath, String packageName) {
            File[] files = new File(packagePath).listFiles(new FileFilter() {
                public boolean accept(File file) {
                    return (file.isFile() && file.getName().endsWith(".class")) || file.isDirectory();
                }
            });
            for (File file : files) {
                String fileName = file.getName();
                if (file.isFile()) {
                    String className = fileName.substring(0, fileName.lastIndexOf("."));
                    if (StringUtil.isNotEmpty(packageName)) {
                        className = packageName + "." + className;
                    }
                    doAddClass(classSet, className);
                } else {
                    String subPackagePath = fileName;
                    if (StringUtil.isNotEmpty(packagePath)) {
                        subPackagePath = packagePath + "/" + subPackagePath;
                    }
                    String subPackageName = fileName;
                    if (StringUtil.isNotEmpty(packageName)) {
                        subPackageName = packageName + "." + subPackageName;
                    }
                    addClass(classSet, subPackagePath, subPackageName);
                }
            }
        }
    
        private static void doAddClass(Set<Class<?>> classSet, String className) {
            Class<?> cls = loadClass(className, false);
            classSet.add(cls);
        }
    }
    
    
    
    
    
    
    
    
    

    相关文章

      网友评论

          本文标题:工具类 java枚举类作数据字典,枚举的key和message扫

          本文链接:https://www.haomeiwen.com/subject/vdbkhrtx.html