0

Suppose I have a class structure like :

@MyAnnotationOne
class A { 
    private String id;
    private B b;

    public static class B {
        private C c;

        @MyAnnoationOne
        public static class C {
            @MyAnnotationTwo
            private String annotatedString;
        }
    }
}

I am using annotation processing to generate code. If I'm processing @MyAnnotationOne, then using the Mirror API I can get all the fields in class A and class C.

I want to know if there is any way I could find if any of the fields in class A, going down the hierarchy contain the annotation @MyAnnotationOne or @MyAnnotationTwo. Finding any one would be enough.

I tried looking for a solution but I found some saying that since the annotation processing happens in a pre-compilation stage, the information might not be available. Please let me know if there's any solution that you might know. It'd be a great help.

mysticfyst
  • 347
  • 4
  • 9

1 Answers1

0

You can configure whether annotations are retained into runtime or not. You annotate your own annotation type with the java.lang.annotation.Retention meta-annotation, specifying one of the values from the enum java.lang.annotation.RetentionPolicy.

RUNTIME Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.

CLASS Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time.

SOURCE Annotations are to be discarded by the compiler.

EDIT If you are building an annotation processor:

  • your code is running during that (pre) compilation phase, so all annotations should be present.
  • Mirror API is deprecated, see javax.lang.model... and javax.annotation.processing

If you override javax.annotation.processing.AbstractProcessor.process() you receive a RoundEnvironment with methods for getting model Elements, including sets filtered by specific annotation types. And given an Element you can getEnclosedElements() and on those getAnnotation(annotationType).

Community
  • 1
  • 1
asynchronos
  • 583
  • 2
  • 14