在Java中,@Generated
注解通常用于标记由代码生成工具自动生成的类、方法或字段。如果你想在不可变生成的类中禁用@Generated
注解,可以通过以下几种方式实现:
如果你使用的是Maven或Gradle等构建工具,可以通过配置插件来实现条件编译。
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<compilerArgs>
<arg>-AdisableGeneratedAnnotation=true</arg>
</compilerArgs>
</configuration>
</plugin>
</plugins>
</build>
然后在代码中使用注解处理器来检查这个参数:
@SupportedAnnotationTypes("javax.annotation.Generated")
public class CustomProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (Element element : roundEnv.getElementsAnnotatedWith(Generated.class)) {
if ("true".equals(processingEnv.getOptions().get("disableGeneratedAnnotation"))) {
// 移除@Generated注解
element.getAnnotationMirrors().removeIf(mirror -> mirror.getAnnotationType().asElement().getSimpleName().contentEquals("Generated"));
}
}
return true;
}
}
你可以编写一个自定义的注解处理器,在处理时根据某些条件决定是否保留@Generated
注解。
@SupportedAnnotationTypes("javax.annotation.Generated")
public class DisableGeneratedAnnotationProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (Element element : roundEnv.getElementsAnnotatedWith(Generated.class)) {
// 根据某些条件决定是否移除@Generated注解
if (shouldDisableGeneratedAnnotation(element)) {
element.getAnnotationMirrors().removeIf(mirror -> mirror.getAnnotationType().asElement().getSimpleName().contentEquals("Generated"));
}
}
return true;
}
private boolean shouldDisableGeneratedAnnotation(Element element) {
// 这里可以添加你的逻辑,比如检查类名、包名等
return element.getSimpleName().contentEquals("ImmutableClass");
}
}
如果你不想使用复杂的构建工具配置或注解处理器,可以在生成的代码中手动移除@Generated
注解。
// 假设这是生成的类
public final class ImmutableClass {
// 移除@Generated注解
// @Generated(value = "SomeGenerator", date = "2023-10-01T12:00:00Z")
private final int id;
private final String name;
public ImmutableClass(int id, String name) {
this.id = id;
this.name = name;
}
// Getters...
}
@Generated
注解。@Generated
注解有特殊处理,而你不希望这些处理影响你的不可变类。@Generated
注解的工具或框架。通过上述方法,你可以在不可变生成的类中有效地禁用@Generated
注解,以满足特定的需求。
领取专属 10元无门槛券
手把手带您无忧上云