獲取包下的所有類和獲取類下所有的方法

package demo;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class getClassMain {

     
    public static void main(String[] args) {
        
        Set<String> classNameSet = getClassName("demo",false);
        Set<String> methodNameSet = getMethodNames("demo.getClassMain");
        
        System.out.println("==== 所有的類");
        for(String s : classNameSet){
            
            System.out.println(s);
        }
        
        System.out.println("==== 所有的方法");
        for(String s : methodNameSet){
            System.out.println(s);
        }
    }
    
    
      /**
     * 根據類獲取類中所有方法
     *
     * @param aClass
     * @return
     */
    public static Set<String> getMethodNames(String aClass) {

        Set<String> methodNames = new HashSet<String>();
        //獲取對象類型 包名.類名
        Class<?> classType = null;
        try {
            classType = Class.forName(aClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        if (classType != null) {
            //獲取對象中的所有方法
            Method[] methods = classType.getDeclaredMethods();
            for (Method method : methods) {
                String name = method.getName();
                if (!name.contains("$")) {
                    methodNames.add(name);
                }
            }
        }
        return methodNames;
    }
    
     /**
     * 獲取某包下所有類
     *
     * @param packageName 包名
     * @param isRecursion 是否遍歷子包
     * @return 類的完整名稱
     */
    public static Set<String> getClassName(String packageName, boolean isRecursion) {
        Set<String> classNames = null;
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        String packagePath = packageName.replaceAll("\\.", "\\/");
        URL url = loader.getResource(packagePath);

        if (url != null) {
            String protocol = url.getProtocol();

            if ("file".equals(protocol)) {
                classNames = getClassNameFromDir(url.getPath(), packageName, isRecursion);
            } else if ("jar".equals(protocol)) {
                JarFile jarFile = null;
                try {
                    jarFile = ((JarURLConnection) url.openConnection()).getJarFile();
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                    e.printStackTrace();
                }
                if (jarFile != null) {
                    classNames = getClassNameFromJar(jarFile.entries(), packageName, isRecursion);
                }
            }
        } else {
            /*從所有的jar包中查找包名*/
            classNames = getClassNameFromJars(((URLClassLoader) loader).getURLs(), packageName, isRecursion);
        }

        return classNames;
    }
    
    /**
     * 從項目文件獲取某包下所有類
     *
     * @param filePath    文件路徑
     * @param packageName 類名集合
     * @param isRecursion 是否遍歷子包
     * @return 類的完整名稱
     */
    private static Set<String> getClassNameFromDir(String filePath, String packageName, boolean isRecursion) {
        Set<String> className = new HashSet<String>();
        File file = new File(filePath);
        File[] files = file.listFiles();
        for (File childFile : files) {
            if (childFile.isDirectory()) {
                if (isRecursion) {
                    className.addAll(getClassNameFromDir(childFile.getPath(), packageName + "." + childFile.getName(), isRecursion));
                }
            } else {
                String fileName = childFile.getName();
                if (fileName.endsWith(".class") && !fileName.contains("$")) {
                    className.add(packageName + "." + fileName.replace(".class", ""));
                }
            }
        }

        return className;
    }
    
    /**
     * 從所有jar中搜索該包,並獲取該包下所有類
     *
     * @param urls        URL集合
     * @param packageName 包路徑
     * @param isRecursion 是否遍歷子包
     * @return 類的完整名稱
     */
    private static Set<String> getClassNameFromJars(URL[] urls, String packageName, boolean isRecursion) {
        Set<String> classNames = new HashSet<String>();

        for (int i = 0; i < urls.length; i++) {
            String classPath = urls[i].getPath();

            //不必搜索classes文件夾
            if (classPath.endsWith("classes/")) {
                continue;
            }

            JarFile jarFile = null;
            try {
                jarFile = new JarFile(classPath.substring(classPath.indexOf("/")));
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (jarFile != null) {
                classNames.addAll(getClassNameFromJar(jarFile.entries(), packageName, isRecursion));
            }
        }

        return classNames;
    }
    
    /**
     * @param jarEntries
     * @param packageName
     * @param isRecursion
     * @return
     */
    private static Set<String> getClassNameFromJar(Enumeration<JarEntry> jarEntries, String packageName, boolean isRecursion) {
        Set<String> classNames = new HashSet<String>();

        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();

            if (!jarEntry.isDirectory()) {
                /*
                 * 這裏是爲了方便,先把"/" 轉成 "." 再判斷 ".class" 的做法可能會有bug
                 * (FIXME: 先把"/" 轉成 "." 再判斷 ".class" 的做法可能會有bug)
                 */
                String entryName = jarEntry.getName().replace("/", ".");

                if (entryName.endsWith(".class") && !entryName.contains("$") && entryName.startsWith(packageName)) {
                    entryName = entryName.replace(".class", "");

                    if (isRecursion) {
                        classNames.add(entryName);
                    } else if (!entryName.replace(packageName + ".", "").contains(".")) {
                        classNames.add(entryName);
                    }
                }
            }
        }

        return classNames;
    }

}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章