【问题标题】:How to retrieve metadata in Dartlang?如何在 Dartlang 中检索元数据?
【发布时间】:2013-10-29 19:58:24
【问题描述】:

Dartlang 教程介绍 package:meta https://www.dartlang.org/docs/dart-up-and-running/contents/ch02.html#ch02-metadata

DartEditor 识别元数据,如上述教程所示。本教程还解释了如何创建自定义元数据并检索它。但是没有关于如何检索它的代码示例。

【问题讨论】:

    标签: dart dart-mirrors


    【解决方案1】:

    通过阅读 Polymer.dart 中的@published metadata 等一些实现,我找到了方法。 https://www.dartlang.org/articles/reflection-with-mirrors/ https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-mirrors#id_reflect

    这里是示例代码。

    import 'dart:mirrors';
    
    class todo {
      final String who;
      final String what;
    
      const todo(this.who, this.what);
    }
    
    @todo('akira', 'add something')
    class Foo {
      @todo('naoto', 'do something')
      String fooVariable = 'a';
    
      @todo('kitano', 'change the name')
      void fooMethod() {
    
      }
    }
    
    void main() {
      InstanceMirror im = reflect(new Foo());
      ClassMirror classMirror = im.type;
    
      // ClassMirror
      classMirror.metadata.forEach((metadata) {
        print(metadata.reflectee.who); // -> akira
        print(metadata.reflectee.what); // -> add something
      });
    
      // VariableMirror   
      for (VariableMirror variable in classMirror.variables.values) {
        print(variable.metadata.first.reflectee.who); // -> naoto
        print(variable.metadata.first.reflectee.what); // -> do something
      }
    
      // MethodMirror
      classMirror.methods.values.forEach((MethodMirror method) {
        print(method.metadata.first.reflectee.who); // -> kitano
        print(method.metadata.first.reflectee.what); // -> change the name
      });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 2020-09-05
      • 1970-01-01
      相关资源
      最近更新 更多