代码之家  ›  专栏  ›  技术社区  ›  Arne Deutsch

如何使用“javax.lang.model.element.elementVisitor”?

  •  4
  • Arne Deutsch  · 技术社区  · 16 年前

    我用Java注释处理器进行实验,并尝试理解“JavaX.Lang.Mead”中类的用法。对于我所读到的,我认为元素访问者应该是使用模型的主要方式。但我不明白如何正确使用它。

    我知道访客的模式。到目前为止,我已经使用它来避免迭代元素的子元素(以及子元素的子元素…)并避免丑陋的“instanceof”测试。但这位来访者似乎有所不同。如果我在模型元素上调用“accept”,它不会访问子元素,而是只访问元素本身。

    有人能为如何使用API提供帮助吗?

    我找到了以下链接: http://www.cs.bgu.ac.il/~gwiener/programming/visitors-galore/#more-113 . 但是使用一个访问者在另一个访问者的内部…只是感觉不对!?

    编辑 :为了更容易理解问题,我从上面的链接复制代码。以下代码似乎不“正确”。我不敢相信一个官方Java API是用这种方式设计的。但是如何正确使用elementvisitor呢?

    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 回复  |  直到 16 年前
        1
  •  4
  •   akuhn    16 年前

    这是胡说八道。

    看一看 javax.lang.model.util.ElementKindVisitor6 javax.lang.model.util.ElementScanner6 他们可能会做什么。在任何情况下,你都应该能够获取他们的资源并使他们适应你的需要。

    NB: 尽管如此,我也认为elementVisitor是一个相当奇怪的访问者实现。