Getting ClassMirror instances for all classes that

2019-05-30 15: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条回答
戒情不戒烟
2楼-- · 2019-05-30 16:49

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

查看更多
登录 后发表回答