How to retrieve metadata in Dartlang?

99封情书 提交于 2019-12-30 03:33:09

问题


Dartlang tutorial introduces package:meta https://www.dartlang.org/docs/dart-up-and-running/contents/ch02.html#ch02-metadata

DartEditor recognise the metadata as shown at above tutorial. The tutorial also explains how to create custom metadata and retrieve it. But there is no code sample on how to retrieve it.


回答1:


Through reading some implementations such as @published metadata in Polymer.dart, I find the way. https://www.dartlang.org/articles/reflection-with-mirrors/ https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-mirrors#id_reflect

Here is the sample code.

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
  });
}


来源:https://stackoverflow.com/questions/19492607/how-to-retrieve-metadata-in-dartlang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!