1. 程式人生 > 其它 >類位元組碼檔案掃描工具,不可掃描jar包

類位元組碼檔案掃描工具,不可掃描jar包

/**
 * @description :類位元組碼檔案掃描工具,不可掃描jar包
 */
public class ClassScanner {

    /**
     * 獲得包下面的所有的class
     *
     * @param
     * @return List包含所有class的例項
     */

    public static List<Class<?>> getClasssFromPackage(String packageName) {
        List<Class<?>> clazzs = new ArrayList<>();
        
// 是否迴圈搜尋子包 boolean recursive = true; // 包名對應的路徑名稱 String packageDirName = packageName.replace('.', '/'); Enumeration<URL> dirs; try { dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName); while (dirs.hasMoreElements()) { URL url
= dirs.nextElement(); String protocol = url.getProtocol(); if ("file".equals(protocol)) { String filePath = URLDecoder.decode(url.getFile(), "UTF-8"); findClassInPackageByFile(packageName, filePath, recursive, clazzs); } } }
catch (Exception e) { e.printStackTrace(); } return clazzs; } /** * 在package對應的路徑下找到所有的class */ public static void findClassInPackageByFile(String packageName, String filePath, final boolean recursive, List<Class<?>> clazzs) { File dir = new File(filePath); if (!dir.exists() || !dir.isDirectory()) { return; } // 在給定的目錄下找到所有的檔案,並且進行條件過濾 File[] dirFiles = dir.listFiles(new FileFilter() { public boolean accept(File file) { boolean acceptDir = recursive && file.isDirectory();// 接受dir目錄 boolean acceptClass = file.getName().endsWith("class");// 接受class檔案 return acceptDir || acceptClass; } }); for (File file : dirFiles) { if (file.isDirectory()) { findClassInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, clazzs); } else { String className = file.getName().substring(0, file.getName().length() - 6); try { clazzs.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + "." + className)); } catch (Exception e) { e.printStackTrace(); } } } } }