[英]Is there a Maven plugin for checking annotations presence in code?
I need to ensure that, in specific classes (eg all classes extending some other class), fields annotated with eg @Deprecated are also annotated with @ThisOtherAnnotationMustBeHere.我需要确保,在特定的类中(例如,所有扩展其他类的类),用@Deprecated 等注释的字段也用@ThisOtherAnnotationMustBeHere 注释。
@Deprecated
@ThisOtherAnnotationMustBeHere // this must be present if @Deprecated is also present; otherwise build should fail
private String field;
I need in general something to check for the presence of annotations.我通常需要一些东西来检查注释的存在。
I guess I could write a JUnit test for this using reflection, but I was wondering if there was a Maven solution to this.我想我可以使用反射为此编写 JUnit 测试,但我想知道是否有 Maven 解决方案。
Following @khmarbaise suggestion (thanks!) I've used archunit.org to write a unit test for this. 遵循@khmarbaise 的建议(谢谢!)我已经使用archunit.org为此编写了一个单元测试。 In my case I needed to verify that join fields in JPA entities were annotated with a specific custom JsonAdapter
在我的情况下,我需要验证 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));
}
};
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.