Want to enforce a restriction on a class to not have an annotation of a class that is annotated by a Qualifier Annotation using ArchUnit Below are my classes

@javax.inject.Qualifier
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
Public @Interface Custom
@Custom
class Test(){
}

In above classes, I have an annotation name Custom which is annotated with Qualifier. Now, I want to restrict the usage of Custom annotation to any other class (because Annotation Custom is annotated with Qualifier)

Using Java reflection I am able to restrict it. Below is the code

Set<Class<?>> qualifierClasses = Reflections.getTypesAnnotatedWith(Qualifier.class);
for (Class<?> qualifierclass : qualifierClasses) {
Set<Class<?>> classes = Reflections.getTypesAnnotatedWith((Class<? extends Annotation>) qualifierclass);
if (CollectionUtils.isNotEmpty(qualifiedClasses)) {
      System.out.println("Code Violation found")
}

but I want to implement the same using ArchUnit

1

There are 1 best solutions below

0
Manfred On

ArchUnit supports the concept of meta-annoations, i.e. annotations declared on other annotations. As this includes direct annotations, you need to exclude those explicitly if you don't want @interface Custom to be considered a violation:

    ArchRule rule =
        noClasses()
            .that().areNotAnnotatedWith(Qualifier.class)
            .should().beMetaAnnotatedWith(Qualifier.class);