按类别标记引用类

时间:2014-06-08 22:10:15

标签: dart dart-mirrors

是否可以通过一些元数据注释找到(使用镜像API的概率)所有类(在我的项目中)? 实施例:

import 'baz.dart'; //more tagged classes

@Tag(#foo)
class A{

}
@Tag(#foo)
class B{

}

void main() {
 List<ClassMirror> li = getClassMirrorsByTag(#foo);
}

1 个答案:

答案 0 :(得分:2)

我找到了答案:

<强> getClassMirrorsByTag.dart

library impl;
@MirrorsUsed(metaTargets: Tag)
import 'dart:mirrors';

class Tag {
  final Symbol name;
  const Tag(this.name);
}
List<ClassMirror> getClassMirrorsByTag(Symbol name) {
  List<ClassMirror> res = new List<ClassMirror>();
  MirrorSystem ms = currentMirrorSystem();
  ms.libraries.forEach((u, lm) {
    lm.declarations.forEach((s, dm) {
      dm.metadata.forEach((im) {
        if ((im.reflectee is Tag) && im.reflectee.name == name) {
          res.add(dm);
        }
      });
    });
  });
  return res;
}

<强> extra.dart

library extra;
import 'getClassMirrorsByTag.dart';

@Tag(#foo)
class C {}

<强> main.dart

library  main;
import 'getClassMirrorsByTag.dart';
import 'extra.dart';
@Tag(#foo)
class A{}
@Tag(#baz)
class B{}


void main() {
  print(getClassMirrorsByTag(#foo));
}

<强>输出:

  

[ClassMirror on&#39; A&#39;,ClassMirror on&#39; C&#39;]