赞
踩
官方地址:https://github.com/classgraph/classgraph
ClassGraph具有“反转”Java类和/或反射API的能力,或者具有索引类和资源的能力。例如,Java类和反射API可以告诉你给定类的超类,或者给定类实现的接口,或者可以给你一个类的注释列表;ClassGraph可以找到所有扩展了给定类(给定类的所有子类)的类,或者所有实现给定接口的类,或者所有用给定注释标注的类。Java API可以在特定的ClassLoader中以特定的路径加载资源文件的内容,但ClassGraph可以在所有类加载器中找到并加载所有资源,其路径与给定的模式匹配。
- <dependency>
- <groupId>io.github.classgraph</groupId>
- <artifactId>classgraph</artifactId>
- <version>4.8.139</version>
- </dependency>
示例
- public static void testDemo() {
-
- try (ScanResult scanResult = new ClassGraph().enableAllInfo().acceptPackages("packageName")// packageName为指定路径,如com.xx.yy
- .scan()) {
- ClassInfoList allClasses = scanResult.getAllClasses();
- for (ClassInfo allClass : allClasses
- ) {
- ClassInfoList methodInfo = allClass.getAnnotations();
- MethodInfoList methodInfos = allClass.getMethodInfo();
- String className = allClass.getName();
-
- System.out.println("方法信息:\n" + methodInfo);
- System.out.println("方法信息列表:\n" + methodInfos);
- System.out.println("类名\n" + className);
- }
- }
- }

查找某个路径下,被@xx注解标识的所有类
- public static void testDemo() {
-
- try (ScanResult scanResult = new ClassGraph().enableAllInfo().acceptPackages("packageName")// packageName为指定路径,如com.xx.yy
- .scan()) {
- // 示例为:packageName下,所有被@Test标识的类,返回结果为classA extends classB
- scanResult.getClassesWithAnnotation("org.testng.annotations.Test");
- }
- }
获取接口类名:
allClass.getInterfaces();
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。