Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "javax.lang.model.element.ElementVisitor"?

Tags:

I experiment with java annotation processors and try to understand the usage of the classes in "javax.lang.model". For what I have read I think the ElementVisitor is to be intended as the primary way to work with the model. But I don't understand how to use it properly.

I knew the visitor pattern. Up to now I've used it to avoid iterating over the children of an element (and the children of the children ...) and avoiding ugly "instanceof" tests. But this visitor seems to be different. If I call "accept" on an model element it doesn't visit the children but only the element itself.

Could someone provide assistance on how to make use of the API?

I've found the following link: http://www.cs.bgu.ac.il/~gwiener/programming/visitors-galore/#more-113 . But using one visitor inside the other inside the other ... just feel not right!?

Edit: To make it easier to understand the question I copy the code from the link above. The following code doesn't seem to be "right". I can't believe that an official java API is designed in this way. But how to use the ElementVisitor properly?

tElem.accept(new SimpleElementVisitor6<Void, ...>() {
  public Void visitType(TypeElement e, ...) {
    for (Element tSubElem : e.getEnclosedElements()) {
      tSubElem.accept(new SimpleElementVisitor6<AssocEndSpec, ...>() {
        public AssocEndSpec visitExecutable(ExecutableElement ex, ...) {
          TypeMirror tRetTypeMirror = ex.getReturnType();
          tRetTypeMirror.accept(new SimpleTypeVisitor6<TypeElement, TypeElement>() {
            public TypeElement visitDeclared(DeclaredType t, TypeElement enclose) {
              for (TypeMirror tTypeArgMirror : t.getTypeArguments()) {
                tTypeArgMirror.accept(new SimpleTypeVisitor6<TypeElement, ...>() {
                  public TypeElement visitDeclared(DeclaredType t, TypeElement self) {
                    TypeElement tArgTypeElem = (TypeElement) t.asElement();
                    if (!self.equals(tArgTypeElem)) {
                      // found the little bugger!
                    }
                  }
                }, ...);
              }
            }
          }, ...);
        }
    }, ...);
  }
}, ...);
like image 507
Arne Deutsch Avatar asked Dec 14 '09 13:12

Arne Deutsch


1 Answers

This code is bollocks.

Take a look at javax.lang.model.util.ElementKindVisitor6 or javax.lang.model.util.ElementScanner6, they might do what. In any case, you should be able to take their sources and adapt them to your needs.

 

NB: that being said, yes I'd say too that ElementVisitor is a rather strange implementation of a visitor.

like image 120
akuhn Avatar answered Oct 12 '22 10:10

akuhn