Java從指定目錄下加載class文件

若是須要從 /Users/xxx/IdeaProjects/xxx-demo/xxx-business-core/target/classes 目錄下加載編譯好的類,須要先遞歸出全部的class文件,而後load到JVMjava

public static Set<Class<?>> loadClasses(String rootClassPath) throws Exception {
    Set<Class<?>> classSet = Sets.newHashSet();
    // 設置class文件所在根路徑
    File clazzPath = new File(rootClassPath);

    // 記錄加載.class文件的數量
    int clazzCount = 0;

    if (clazzPath.exists() && clazzPath.isDirectory()) {
        // 獲取路徑長度
        int clazzPathLen = clazzPath.getAbsolutePath().length() + 1;

        Stack<File> stack = new Stack<>();
        stack.push(clazzPath);

        // 遍歷類路徑
        while (!stack.isEmpty()) {
            File path = stack.pop();
            File[] classFiles = path.listFiles(new FileFilter() {
                public boolean accept(File pathname) {
                    //只加載class文件
                    return pathname.isDirectory() || pathname.getName().endsWith(".class");
                }
            });
            if (classFiles == null) {
                break;
            }
            for (File subFile : classFiles) {
                if (subFile.isDirectory()) {
                    stack.push(subFile);
                } else {
                    if (clazzCount++ == 0) {
                        Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
                        boolean accessible = method.isAccessible();
                        try {
                            if (!accessible) {
                                method.setAccessible(true);
                            }
                            // 設置類加載器
                            URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
                            // 將當前類路徑加入到類加載器中
                            method.invoke(classLoader, clazzPath.toURI().toURL());
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            method.setAccessible(accessible);
                        }
                    }
                    // 文件名稱
                    String className = subFile.getAbsolutePath();
                    className = className.substring(clazzPathLen, className.length() - 6);
                    //將/替換成. 獲得全路徑類名
                    className = className.replace(File.separatorChar, '.');
                    // 加載Class類
                    Class<?> aClass = Class.forName(className);
                    classSet.add(aClass);
                    System.out.println("讀取應用程序類文件[class={" + className + "}]");
                }
            }
        }
    }
    return classSet;
}
相關文章
相關標籤/搜索