Home > Blockchain >  Find where annotation is processed
Find where annotation is processed

Time:11-03

I often find myself trying to figure out how a particular annotation works under the hood. Performing a 'find usages' on the annotation in the IDE(like IntelliJ) will usually just bring you to where the annotation is actually used. I don't see an easy way however of finding the logic that processes the annotation.

I get that because of the nature of annotations that it's difficult to see where they are being processed, but at the same time, when they are consumed one would have had to import the specific annotation so there is a link established.

Take the case of

SomeAnnotation.java

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

and it's being consumed in AnnotationConsumer.java

import com.annotations.SomeAnnotation
public class AnnotationProcessor {

  public AnnotationProcessor() {
    if (currentClass.isAnnotationPresent(SomeAnnotation.class)) {
      // do some logic
    }
  }
}

Usually, some piece of code will be tagged with @SomeAnnotation.

What I would like to do is find the AnnotationProcessor class where SomeAnnotation is being processed.

Anything I've searched for so far simply leads me down a path of HOW to process annotations, not WHERE they are being processed.

CodePudding user response:

If it is about runtime annotation processor, then debug the application in IDEA, put a conditional break point on Class.isAnnotationPresent(Class<? extends Annotation> a) method.

condition is a.equals(SomeAnnotation.class).

debug will be slow because of conditional break point, but you may find out the call stack when break point hit.

CodePudding user response:

You didn't specify whether you are thinking of compile-time annotation processing or run-time annotation processing.

For compile-time annotation processing, the annotation processor is either listed on the command line after a -processor flag, or (for automatic discovery) it is listed in a file named META-INF/services/javax.annotation.processing.Processor that is on the search path. See https://docs.oracle.com/en/java/javase/17/docs/specs/man/javac.html .

  • Related