1. 程式人生 > >通過專案下的包名獲取包下的全部類

通過專案下的包名獲取包下的全部類

通過專案下的包名獲取包下的全部類

public class GetClasses {

    public static Set<Class<?>> classes = new HashSet<>();

    public static void main(String[] args) {
        GetAllClass("com.bihang.seayatest.nio");
        System.out.println(classes.size());
    }

    public static void GetAllClass(String packageName){
        Enumeration<URL> dirs = null;
        try {
            dirs = Thread.currentThread().getContextClassLoader().getResources(packageName.replace(".","/"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (dirs.hasMoreElements()){
            //獲取物理路徑
            String filePath = dirs.nextElement().getFile();
            addPathToClasses(filePath,packageName,classes);
        }
    }

    public static void addPathToClasses(String classPath, String rootPackageName, Set<Class<?>> classes) {
        File file = new File(classPath);
        if (!file.exists() && !file.isDirectory())
            return;

        if (file.isDirectory()) {
            File[] list = file.listFiles();
            //如果是資料夾就需要在包名後面新增檔名
            for (File path :
                    list) {
                if (path.isDirectory())
                    addPathToClasses(path.getAbsolutePath(), rootPackageName+"."+path.getName(), classes);
                else
                    addPathToClasses(path.getAbsolutePath(), rootPackageName, classes);
            }
        } else {
            if (file.getName().endsWith(".class")){
                String className = file.getName().substring(0,
                        file.getName().length() - 6);
                try {
                    classes.add(Thread.currentThread().getContextClassLoader().loadClass(rootPackageName + '.'+ className));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

getName()方法

返回檔名稱,包括字尾.

list()方法

返回檔名的陣列,是String的陣列。

listFiles()方法

返回檔案的陣列,也就是絕對路徑的陣列。

accept()方法

listFiles()方法會為此目錄物件下的每一個檔名呼叫accpet()方法,來判斷該檔案是否包含在內,判斷結果由accept()方法返回的布林值表示。

exists()

建立之前,要通過file.exists()判斷該檔案或者資料夾是否已經存在,如果返回true,是不能建立的。