gpt4 book ai didi

java - Maven 编译器,只编译带注解的类

转载 作者:行者123 更新时间:2023-11-30 09:13:37 24 4
gpt4 key购买 nike

我在我正在处理的 Maven 2 项目中创建了一个自定义 Java 注释(下面的代码):

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MYANNOTATION{}

在 Maven 构建的一部分,我只想编译用这个注释注释的类,例如:

@MYANNOTATION
public class MyClass {
// Code here
}

我目前正在使用 Maven Compiler Plugin限制基于包结构的并发症。我的 pom.xml 包含类似于下面的内容,将编译限制为 **com.foo.bar.stuff** 和 **com.baz.foo.more** 中的类。这并不令人满意,因为当我向 com.xyz.bar.foo 添加带注释的类时,我必须记得在 pom 中定义它。

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<executions>
<execution>
<id>default-compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<includes>
<include>**/com/foo/bar/stuff/**</include>
<include>**/com/baz/foo/more/**</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>

有什么方法可以定义 Maven 只编译已经用这个注释注释的类,而不依赖于它们在包层次结构中的位置?

(我正在尝试从域模型类生成元模型,这样我就可以指向字段和方法,而无需将名称定义为字符串常量 - 并在重构时手动更改它们)

编辑:我已经在构建阶段的另一部分进行注释处理。该系统是这样工作的:

  1. 编译指定包中的类
  2. 使用JAnnocessor , 使用 @MYANNOTATION 从类构建元模型
  3. 编译其余类

从其他类到元模型类的依赖性阻止一次性编译所有内容,除非我们将带注释的类移动到不同的项目并向其添加依赖性。这是一种可能性,但会增加复杂性,因为当前的项目结构似乎形成了一个逻辑整体。

最佳答案

您可以使用注释处理做一些类似于您想要的事情。我不认为您需要做任何特定于 Maven 的事情,但您需要编写一个注释处理器,它必须是单独库的一部分或单独编译。

注释处理的概念在这篇博文中得到了很好的解释:

Code Generation using Annotation Processors in the Java language – part 2: Annotation Processors

关于java - Maven 编译器,只编译带注解的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20969409/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com