zoukankan      html  css  js  c++  java
  • 代码片段,得到所有实现接口且在同包下的类

    /**
         * 得到所有实现接口而且在同包下的的类
         * @param aClass
         * @return
         * @throws IOException
         * @throws ClassNotFoundException
         */
        public List<Class> getImplClass(Class aClass) throws IOException, ClassNotFoundException {
            List<Class> list = new ArrayList<>();
            List<Class> resultList = new ArrayList<>();
            String aPackage=aClass.getPackage().getName();
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            Enumeration<URL> enumeration =classLoader.getResources(aPackage.replaceAll("\.","/"));
            while (enumeration.hasMoreElements()) {
                list.addAll(findClass(enumeration.nextElement().getPath(), aPackage));
            }
            for (Class c:list) {
                if (isImplInterface(c) && !aClass.equals(c) && !resultList.contains(c)) {
    
                    resultList.add(c);
                }
            }
            resultList.add(0,Class.forName("com.huawei.SysCode"));
            return resultList;
        }
    
        private boolean isImplInterface(Class aClass) {
            
            Class[] classes=aClass.getInterfaces();
            for (Class c : classes) {
                if(INTERFACE_CLASS.equals(c.getName()) {
                    return true;
                }
            }
            return false;
        }
    
        /**
         * 得到路径下所有class
         * @param dir
         * @param packageName
         * @return
         * @throws ClassNotFoundException
         */
        private List<Class> findClass(String dir, String packageName) throws ClassNotFoundException {
            List<Class> list = new ArrayList<>();
            File f = new File(dir);
            if (!f.exists()) {
                return list;
            }
            File[] files=f.listFiles();
            for (File file : files) {
                if (file.isDirectory())) {
                    list.addAll(findClass(file.getPath(), packageName+"."+file.getName()));
                }else if(file.getName().matches(".+\.class$")){
                    list.add(Class.forName(packageName+"."+file.getName().replaceAll("\.class$","")));
                }
            }
            return list;
        }
    

      

  • 相关阅读:
    简单排序
    vue router在history模式下 如何部署在tomcat上
    概率论复习纲要
    MyBatis学习笔记(持续更新 2021/01/06- 2021/01/10)
    JavaWeb学习笔记(持续编辑2021/1/5-)
    2021/01/10周学习总结
    将WiFi搞得可以认证石铁大校园网(小米3路由器)
    对老师的建议
    自我感觉加分项
    github、gitee冲突配置ssh key
  • 原文地址:https://www.cnblogs.com/zhangminjie/p/4349170.html
Copyright © 2011-2022 走看看