views:

100

answers:

1

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!
                    }
                  }
                }, ...);
              }
            }
          }, ...);
        }
    }, ...);
  }
}, ...);
+1  A: 

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.

Adrian
ElementScanner6 was what I looking for. Althought I'm still unsure what to do with the other implementations ... without traversal of the composite they seem rather useless. Thx for the tip!
Arne