Custom Annotation processor not being invoked by tomcat

1.1k Views Asked by At

Custom Annotation processor is not being invoked by tomcat. Following is the Annotation processor code that I am using :

@SuppressWarnings("restriction")
@SupportedAnnotationTypes("io.strati.rs.cxf2.bindings.MyAnnotation")
@SupportedSourceVersion( SourceVersion.RELEASE_8 )
public class SimpleAnnotationProcessor extends AbstractProcessor {

    public static List<String> str = new ArrayList<>();

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

        System.out.println("Into annotation processor ... 2");

        for ( Element element : roundEnv.getElementsAnnotatedWith(MyAnnotation.class)) {
            System.out.println("Method name is:"+element.getSimpleName());
            str.add(element.getSimpleName().toString());
        }   
        return false;
    }
}

This stores the method name of all the methods that have the custom annotation. This is what the annotation class looks like :

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyAnnotation {

}

I am trying to access the list in a tomcat application as follows :

@GET
@Path("/dummy")
@MyAnnotation
@Produces({APPLICATION_JSON, APPLICATION_XML, TEXT_XML})
public void print(){
   System.out.println("List is:"+SimpleAnnotationProcessor.str);
}

The list is getting printed as empty even though the method has the annotation.I have specified the annotation in the maven compiler plugin as well as specified it in META-INF/services/javax.annotation.processing.Processor. Can someone tell me what are the possible reasons due to which the annotation processor is not getting invoked ?

1

There are 1 best solutions below

0
On BEST ANSWER

I doubt Tomcat has anything to do with it. Annotation processing takes place at compile time and is often used to generate or modify code. An annotation processor can be seen as a compiler plugin.

https://www.javacodegeeks.com/2015/09/java-annotation-processors.html

Following the retention policy, the annotation is going to be retained by Java compiler in the class file during the compilation phase however it will not be (and should not be) available at runtime.

It's likely the annotation processor is in fact adding the print() method name to the list (check the build output), but again this only happens when compiling the code.

The deployed web service at runtime is never going to see the list filled by the processor at compile time, those are completely different environments.