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

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

  

posted @ 2015-03-19 00:10  脱氧  阅读(116)  评论(0编辑  收藏  举报