获取具有注释的所有类的ClassMirror实例

时间:2014-06-27 17:07:00

标签: dart dart-mirrors

我有这个注释

class Target{
  final String value;
  const Target(this.value);
}

和2个用它注释的类

@Target("/313")
class c1{

}

@Target("/314")
class c2{

}

如何获取具有Target注释的类的ClassMirror实例列表?

基于所选答案,如果我知道我的calsses存在于

中的库
  var mirrorSystem = currentMirrorSystem();
  var libraryMirror = mirrorSystem.findLibrary(#testlib);
  for(ClassMirror classMirror in libraryMirror.declarations.values){
    if(classMirror.metadata!=null){
      for(var meta in classMirror.metadata){
            if(meta.type == reflectClass(Path)){
              print(classMirror.simpleName);
              print(meta.getField(#value));
            }
          }
    }
  }

1 个答案:

答案 0 :(得分:4)

这将搜索当前隔离中的所有库,以查找使用@Target('/313')

注释的类
@MirrorsUsed(metaTargets: Target) // might be necessary when you build this code to JavaScript
import 'dart:mirrors';

class Target {
  final String id;
  const Target(this.id);
}

@Target('/313')
class c1{

}

@Target('/314')
class c2{

}

@Target('/313')
@Target('/314')
class c3{

}

void main() {
  MirrorSystem mirrorSystem = currentMirrorSystem();
  mirrorSystem.libraries.forEach((lk, l) {
    l.declarations.forEach((dk, d) {
      if(d is ClassMirror) {
        ClassMirror cm = d as ClassMirror;
        cm.metadata.forEach((md) {
          InstanceMirror metadata = md as InstanceMirror;
          if(metadata.type == reflectClass(Target) && metadata.getField(#id).reflectee == '/313') {
            print('found: ${cm.simpleName}');
          }
        });
      }
    });
  });
}
  

发现:符号(" c3")
  找到:符号(" c1")