0

我想获取 TypeAnnotation 源以获取在该类型上定义的注释

// file1.dart

@Annoation(name :"hello")
class RType { }

// file2.dart

    @Selectors()
    class Example {
      static Rtype hello() => null;
    }

通过使用 ast visitor,我可以获得 RType(TypeAnnoation),但我想获得实际的 RType 及其注释..

class SelectorsGenerator extends GeneratorForAnnotation<Selectors> {

AstNode getAstNodeFromElement(Element element) {
  AnalysisSession session = element.session;
  ParsedLibraryResult parsedLibResult =
      session.getParsedLibraryByElement(element.library);
  ElementDeclarationResult elDeclarationResult =
      parsedLibResult.getElementDeclaration(element);
  return elDeclarationResult.node;
}

  @override
  generateForAnnotatedElement(
      Element element, ConstantReader annotation, BuildStep buildStep) {
    if (!(element is ClassElement)) {
      throw Exception("Selectors should be applied on class only");
    }
    element = element as ClassElement;

    final visitor = ExampleVisitor();
    final astNode = getAstNodeFromElement(element);
    astNode.visitChildren(visitor);

    return """
       // Selector
    """;
  }
}


class ExampleVisitor extends SimpleAstVisitor {
        
     @override
     visitMethodDeclaration(MethodDeclaration node) {
             final t= node.returnType; //TypeAnnonation
              t.type // DartType is null here :( 
              //TODO i want to get annotations defined on this type 
        
           }
        }
4

1 回答 1

1

您不需要为此切换到 AST 模型,应该可以使用 Element 模型获取注释。

var methods = classElement.methods;
for (var method in methods) {
  var returnType = method.returnType;
  var metadata = returnType.element.metadata;
  // Do something with the annotation.
}
于 2020-10-29T18:10:48.657 回答