Search code examples
dartdart-mirrors

Getting ClassMirror instances for all classes that have an annotation


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));
            }
          }
    }
  }

Solution

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