You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Maven插件中访问带有特定注解的类?

Maven插件如何访问带有特定注解的类?

我想通过Maven插件访问项目中带有特定注解的类,现有代码如下:

@SuppressWarnings("unused")
@Parameter(defaultValue = "NotSet")
private String forecast;

@SuppressWarnings("unused")
@Parameter(defaultValue = "${project}")
private MavenProject mavenProject;

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    getLog().debug("Executing");
    // Accessing the maven project and getting the classes
    getLog().debug("Stopping");
}

尝试用Reflections库但无法作用于目标Maven项目,求解决思路。


解决方案

1. 配置@Mojo注解

给Mojo类添加注解配置,确保插件能获取到项目编译阶段的依赖:

@Mojo(name = "generator", defaultPhase = LifecyclePhase.COMPILE, requiresDependencyResolution = ResolutionScope.COMPILE)

2. 实现类路径加载与注解扫描

在execute方法中,通过MavenProject获取项目编译类路径,构建自定义类加载器后,传给Reflections完成注解扫描:

List<String> classpathElements = null;
try {
    classpathElements = mavenProject.getCompileClasspathElements();
    List<URL> projectClasspathList = new ArrayList<URL>();
    for (String element : classpathElements) {
        try {
            projectClasspathList.add(new File(element).toURI().toURL());
        } catch (MalformedURLException e) {
            throw new MojoExecutionException(element + " is an invalid classpath element", e);
        }
    }

    URLClassLoader loader = new URLClassLoader(projectClasspathList.toArray(new URL[0]));
    // 示例:加载指定类并打印其注解
    Class clazz = Class.forName("com.example.demo.DemoApplication", true, loader);
    Arrays.stream(clazz.getAnnotations())
            .forEach(System.out::println);
    // 使用Reflections扫描带有指定注解的类
    Reflections reflections = new Reflections(loader);
    reflections.getTypesAnnotatedWith(CuspidsApi.class)
            .forEach(System.out::println);
} catch (ClassNotFoundException e) {
    throw new MojoExecutionException(e.getMessage());
} catch (DependencyResolutionRequiredException e) {
    throw new MojoExecutionException("Dependency resolution failed", e);
}

内容的提问来源于stack exchange,提问作者DO QUOC VIET

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 08:25:34