类字节码文件扫描工具,不可扫描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(); } } } } }
本文作者:zydjjcpdszylddpll
本文链接:https://www.cnblogs.com/jyfs/p/15103245.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步