Search code examples
javaannotationsannotation-processing

Get Element where TypeElement is defined in?


I have the following class:

public class Start extends PlacePresenter {

    @NameToken("startPage")
    public interface MyProxy extends ProxyPlace {
    }
}

In an annotation processor I got the Element annotated with @NameToken which is MyProxy.

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

  for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(NameToken.class)) {

    TypeElement typeElement = (TypeElement) annotatedElement;
    // typeElement is MyProxy
  }
}

How do I get the Element of the class MyProxy is defined in, i.e., Start?


Solution

  • The containing class will be represented by the Element returned by calling annotatedElement.getEnclosingElement():

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(NameToken.class)) {
            System.out.println(annotatedElement.getEnclosingElement()); // prints "Start"
        }
        return true;
    }