Refer classes by their metadata tag

断了今生、忘了曾经 提交于 2019-11-26 18:38:00

问题


Is it possible to find(probably with the mirror API) all classes(in my project) with some metadata annotation?

Example:

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

@Tag(#foo)
class A{

}
@Tag(#foo)
class B{

}

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

回答1:


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']



来源:https://stackoverflow.com/questions/24111378/refer-classes-by-their-metadata-tag

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