如何从项目src目录加载.kt文件并筛选包含enum关键字的文件
Java项目扫描所有包含enum的文件实现方案
分两种常见需求场景提供对应实现:
场景1:编译后运行环境找所有枚举类
如果需要在运行时识别项目中所有的枚举类,用原生Java即可实现:
- 先将需要扫描的包路径转换为资源路径,使用类加载器获取该路径下的所有资源
- 递归遍历所有
.class文件,加载类后用Class.isEnum()判断是否为枚举类
示例代码:
import java.io.File; import java.net.URISyntaxException; import java.net.URL; import java.util.Enumeration; public class EnumScanner { public static void main(String[] args) throws URISyntaxException, Exception { // 替换为你需要扫描的基础包 String basePackage = "com.your.project"; String basePath = basePackage.replace('.', '/'); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Enumeration<URL> resources = classLoader.getResources(basePath); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); File dir = new File(resource.toURI()); scanClassDir(dir, basePackage); } } private static void scanClassDir(File dir, String packageName) throws ClassNotFoundException { if (!dir.exists() || !dir.isDirectory()) return; File[] files = dir.listFiles(); if (files == null) return; for (File file : files) { if (file.isDirectory()) { scanClassDir(file, packageName + "." + file.getName()); } else if (file.getName().endsWith(".class")) { String className = packageName + "." + file.getName().replace(".class", ""); Class<?> clazz = Class.forName(className); if (clazz.isEnum()) { // 匹配到枚举类,此处执行你需要的业务逻辑 System.out.println("找到枚举类:" + className); } } } } }
场景2:源码环境找包含enum关键字的文件
如果是需要扫描源码目录下所有写了enum的.java文件,直接遍历源码目录逐文件匹配即可:
示例代码:
import java.io.File; import java.io.IOException; import java.nio.file.Files; public class SourceEnumScanner { public static void main(String[] args) throws IOException { // 替换为你的源码根目录路径 File sourceRoot = new File("src/main/java"); scanSourceDir(sourceRoot); } private static void scanSourceDir(File dir) throws IOException { if (!dir.exists() || !dir.isDirectory()) return; File[] files = dir.listFiles(); if (files == null) return; for (File file : files) { if (file.isDirectory()) { scanSourceDir(file); } else if (file.getName().endsWith(".java")) { String content = Files.readString(file.toPath()); if (content.contains("enum")) { // 匹配到包含enum的源码文件,此处执行你需要的业务逻辑 System.out.println("找到包含enum的源码文件:" + file.getAbsolutePath()); } } } } }
特殊场景适配
- 如果是Spring项目,可以直接用
PathMatchingResourcePatternResolver简化资源扫描逻辑,无需手写递归:PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); // 匹配指定包下所有class文件 Resource[] resources = resolver.getResources("classpath*:com/your/project/**/*.class"); - 如果是jar包运行环境,需要用
JarFile遍历jar内的条目判断,不能直接用本地文件扫描逻辑。
内容的提问来源于stack exchange,提问作者J_Strauton
相关产品推荐
相关产品推荐

