Maven插件Reflections无法获取注解方法集合?-灵析社区

导师小jio

有如下 Maven 插件代码: @Mojo(name = "generate") public class GenerateMojo extends AbstractMojo { @Parameter(defaultValue = "${project.build.outputDirectory}", required = true) private File outputDirectory; @Parameter private File outputFile; @Override public void execute() throws MojoExecutionException, MojoFailureException { Set permissionCodeSet = new HashSet(); URL url; try { url = outputDirectory.toURI().toURL(); } catch (MalformedURLException e) { throw new RuntimeException(e); } getLog().info(url.toString()); Reflections reflections = new Reflections( new ConfigurationBuilder() .addUrls(url) .setScanners(MethodsAnnotated)); reflections.getStore().forEach((s, stringSetMap) -> { stringSetMap.forEach((k, v) -> { System.out.println(k); v.forEach(System.out::println); System.out.println(); }); }); Set resources = reflections.get(MethodsAnnotated.with(GetMapping.class).as(Method.class)); System.out.println("resources = " + resources); Set methodSet = reflections.get(MethodsAnnotated.with(SaCheckPermission.class).as(Method.class)); getLog().info(methodSet.toString()); methodSet.forEach(method -> { SaCheckPermission saCheckPermission = method.getAnnotation(SaCheckPermission.class); List values = List.of(saCheckPermission.value()); permissionCodeSet.addAll(values); }); getLog().info(permissionCodeSet.toString()); } } Reflections 能够正确实例化并扫描成功,日志如下: [INFO] Reflections took 67 ms to scan 1 urls, producing 7 keys and 79 values 尝试打印 store 内容也正确,但 methodSet 和 permissionCodeSet 均为空 尝试在使用插件的项目中运行上述代码,能够正常输出内容。

阅读量:121

点赞量:0

问AI
可能的问题与排查步骤: 1. 扫描范围确认 : 确保 "outputDirectory" 指向的目录包含了含有 "GetMapping" 和 "SaCheckPermission" 注解的方法的已编译类文件。 2. 类加载与注解保留策略 : 确认 "GetMapping" 和 "SaCheckPermission" 注解的保留策略为 "RUNTIME",允许在运行时通过反射获取注解信息。同时,确保类加载器能够正确加载这些类文件。 3. 注解使用核查 : 检查代码中 "GetMapping" 和 "SaCheckPermission" 注解是否正确应用在方法级别,并且在待扫描的类中确实存在这些注解。 4. 注解处理器校验 : 确认 "MethodsAnnotatedScanner" 正确实现了发现带有指定注解方法的功能。 为进一步解决此问题,推荐在代码中增加详细的日志输出,以便精准了解 "Reflections" 是否在扫描过程中涵盖了期望的类和方法。同时,全面审核目标项目中注解的实际使用情况和构建流程也是至关重要的。