Refer classes by their metadata tag

瘦欲@ 提交于 2019-11-27 16:27:37

I have found the answer:

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

output:

[ClassMirror on 'A', ClassMirror on 'C']

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