How retrieve function that marks with metadata

2019-07-04 16:57发布

问题:

Look at the following code snippet.

import "dart:mirrors";

class meta {
    final String data;

    const meta(this.data);
}


@meta("Tag")
doSomething() => print("You have to do something");

void main() {
    doSomething();
}

How can I retrieve functions, that is market with metadata tags? In my example, I want to find out, which method is marked with meta tags.

回答1:

you could do something like this:

void main() {
    doSomething();
    getMetaData();
}

void getMetaData() {
  LibraryMirror currentLib = currentMirrorSystem().libraries.values.last;
  currentLib.declarations.forEach((Symbol s, DeclarationMirror mirror) {
    if(mirror.metadata.length > 0) {
      print('Symbol $s has MetaData: "${mirror.metadata.first.reflectee.data}"');
    }
  });
}

This should give you:

You have to do something
Symbol Symbol("doSomething") has MetaData: "Tag"

You could also analyze your files from another project and use dart:mirrors on that file instead of inspecting the current library. Maybe libraries.values.last will not always return the current library - so you might need to change it. In my case it worked.



回答2:

var decls = currentMirrorSystem().isolate.rootLibrary.declarations;
print(decls.keys.where((k) => decls[k] is MethodMirror && 
    decls[k].metadata.where((k) => k.reflectee is meta).isNotEmpty));

see also How can i test the existence of a function in Dart?