Getting ClassMirror instances for all classes that have an annotation

守給你的承諾、 提交于 2019-12-10 11:34:54

问题


I have this annotation

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

and 2 classes that are annotated with it

@Target("/313")
class c1{

}

@Target("/314")
class c2{

}

how can i get a List of ClassMirror instances for the classes that have the Target annotation?

based on the selected answer that is if i knew what library my calsses exist in

  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:


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")



来源:https://stackoverflow.com/questions/24457283/getting-classmirror-instances-for-all-classes-that-have-an-annotation

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