How retrieve function that marks with metadata

好久不见. 提交于 2019-12-10 18:17:54

问题


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?



来源:https://stackoverflow.com/questions/26603981/how-retrieve-function-that-marks-with-metadata

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