• 代码片段,得到所有实现接口且在同包下的类


    /**
         * 得到所有实现接口而且在同包下的的类
         * @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;
        }
    

      

  • 相关阅读:
    libevent 源码学习四 —— 源代码文件组织
    c++上待解决的内容
    常用网址
    tin mission 2021 11 14
    问题--c++
    小思维--c++
    thin mission 2021 11 13
    physics--lecture--Centre of Gravity & Inertia and conservation of angular momentum
    physics--lecture--torque--static equilibrium
    physics—lecture ——torque
  • 原文地址:https://www.cnblogs.com/zhangminjie/p/4349170.html
Copyright © 2020-2023  润新知