是否有用于检查代码中是否存在注释的 Maven 插件?
Is there a Maven plugin for checking annotations presence in code?
我需要确保在特定的 classes(例如所有 classes 扩展一些其他 class)中,字段注释为例如@Deprecated 也用@ThisOtherAnnotationMustBeHere 注释。
@Deprecated
@ThisOtherAnnotationMustBeHere // this must be present if @Deprecated is also present; otherwise build should fail
private String field;
我通常需要一些东西来检查是否存在注释。
我想我可以使用反射为此编写一个 JUnit 测试,但我想知道是否有 Maven 解决方案。
(thanks!) I've used archunit.org为此编写单元测试。在我的例子中,我需要验证 JPA 实体中的连接字段是否使用特定的自定义注释 JsonAdapter
class CodeChecksTest {
@ArchTest
public static final ArchRule persistenceIdAnnotationRule = fields().that()
.areDeclaredInClassesThat().areAnnotatedWith(Entity.class).and()
.areAnnotatedWith(OneToOne.class).or()
.areAnnotatedWith(OneToMany.class).or()
.areAnnotatedWith(ManyToOne.class).or()
.areAnnotatedWith(ManyToMany.class)
.should(beAnnotatedForMyCustomAdapter());
private static ArchCondition<? super JavaField> beAnnotatedForMyCustomAdapter() {
return new ArchCondition<JavaField>("annotated with @JsonAdapter(MyCustomAdapter.class)") {
@Override
public void check(JavaField item, ConditionEvents events) {
final Optional<JsonAdapter> annotation = item.tryGetAnnotationOfType(JsonAdapter.class);
final boolean satisfied = annotation.isPresent() && annotation.get().value() == MyCustomAdapter.class;
// createMessage is a utility method
String message = createMessage(item,
(satisfied ? "is " : "is not ") + getDescription());
events.add(new SimpleConditionEvent(item, satisfied, message));
}
};
}
}
我需要确保在特定的 classes(例如所有 classes 扩展一些其他 class)中,字段注释为例如@Deprecated 也用@ThisOtherAnnotationMustBeHere 注释。
@Deprecated
@ThisOtherAnnotationMustBeHere // this must be present if @Deprecated is also present; otherwise build should fail
private String field;
我通常需要一些东西来检查是否存在注释。
我想我可以使用反射为此编写一个 JUnit 测试,但我想知道是否有 Maven 解决方案。
JsonAdapter
class CodeChecksTest {
@ArchTest
public static final ArchRule persistenceIdAnnotationRule = fields().that()
.areDeclaredInClassesThat().areAnnotatedWith(Entity.class).and()
.areAnnotatedWith(OneToOne.class).or()
.areAnnotatedWith(OneToMany.class).or()
.areAnnotatedWith(ManyToOne.class).or()
.areAnnotatedWith(ManyToMany.class)
.should(beAnnotatedForMyCustomAdapter());
private static ArchCondition<? super JavaField> beAnnotatedForMyCustomAdapter() {
return new ArchCondition<JavaField>("annotated with @JsonAdapter(MyCustomAdapter.class)") {
@Override
public void check(JavaField item, ConditionEvents events) {
final Optional<JsonAdapter> annotation = item.tryGetAnnotationOfType(JsonAdapter.class);
final boolean satisfied = annotation.isPresent() && annotation.get().value() == MyCustomAdapter.class;
// createMessage is a utility method
String message = createMessage(item,
(satisfied ? "is " : "is not ") + getDescription());
events.add(new SimpleConditionEvent(item, satisfied, message));
}
};
}
}