Getting ClassMirror instances for all classes that have an annotation

两盒软妹~` 提交于 2019-12-08 04:32:29

This searches all libraries in the current isolate for classes that are annotated with @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}');
          }
        });
      }
    });
  });
}

found: Symbol("c3")
found: Symbol("c1")

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