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

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

/**
 * @description :類位元組碼檔案掃描工具,可以掃描jar包
 */
public class Utils {
    //從包路徑下掃描
    public static Set<Class> getClasses(String packagePath) {
        Set<Class> res = new HashSet<>();
        String path = packagePath.replace(".", "/");
        URL url = Thread.currentThread().getContextClassLoader().getResource(path);
        
if (url == null) { System.out.println(packagePath + " is not exit"); return res; } String protocol = url.getProtocol(); if ("jar".equalsIgnoreCase(protocol)) { try { res.addAll(getJarClasses(url, packagePath)); }
catch (IOException e) { e.printStackTrace(); return res; } } else if ("file".equalsIgnoreCase(protocol)) { res.addAll(getFileClasses(url, packagePath)); } return res; } //獲取file路徑下的class檔案 private static Set<Class> getFileClasses(URL url, String packagePath) { Set
<Class> res = new HashSet<>(); String filePath = url.getFile(); File dir = new File(filePath); String[] list = dir.list(); if (list == null) return res; for (String classPath : list) { if (classPath.endsWith(".class")) { classPath = classPath.replace(".class", ""); try { Class<?> aClass = Class.forName(packagePath + "." + classPath); res.add(aClass); } catch (ClassNotFoundException e) { e.printStackTrace(); } } else { res.addAll(getClasses(packagePath + "." + classPath)); } } return res; } //使用JarURLConnection類獲取路徑下的所有類 private static Set<Class> getJarClasses(URL url, String packagePath) throws IOException { Set<Class> res = new HashSet<>(); JarURLConnection conn = (JarURLConnection) url.openConnection(); if (conn != null) { JarFile jarFile = conn.getJarFile(); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry jarEntry = entries.nextElement(); String name = jarEntry.getName(); if (name.contains(".class") && name.replaceAll("/", ".").startsWith(packagePath)) { String className = name.substring(0, name.lastIndexOf(".")).replace("/", "."); try { Class clazz = Class.forName(className); res.add(clazz); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } } return res; } }