Executing bundle of functions by their metadata tag in Dart lang

↘锁芯ラ 提交于 2019-11-28 11:28:45

问题


Building on this, I want to write a code that run A:: the functions refeed by the same metadata tag.

I tunes the codes of the previous thread as below:

getFunctionMirrorsByTag.dart

library impl;
@MirrorsUsed(metaTargets: Tag)
import 'dart:mirrors';

class Tag {
  final Symbol name;
   const Tag(this.name);
 }
 List<ClassMirror> getClassMirrorsByTag(Symbol name) {
  List res = new List();
  MirrorSystem ms = currentMirrorSystem();
  ms.libraries.forEach((u, lm) {
  lm.declarations.forEach((s, dm) {
  dm.metadata.forEach((im) {
    if ((im.reflectee is Tag) && im.reflectee.name == name) {
      res.add(dm);     // I want to replace this by a statement executing the returned function
       }
     });
    });
  });
  return res;
}

main.dart:

library  main;
import 'getFunctionMirrorsByTag.dart';
import 'extra.dart';
 @Tag(#foo)
    printa()=>print('a');

 @Tag(#foo)
  printb()=>print('b');


 void main() {
    print(getClassMirrorsByTag(#foo));
 }

Using the above, the output I get is:

[MethodMirror on 'printa', MethodMirror on 'printb']

回答1:


@MirrorsUsed(metaTargets: Tag)
import 'dart:mirrors';

class Tag {
  final Symbol name;
  const Tag(this.name);
}
List getMirrorsByTag(Symbol name) {
  List res = new List();
  MirrorSystem ms = currentMirrorSystem();
  ms.libraries.forEach((u, lm) {
    lm.declarations.forEach((s, dm) {
      dm.metadata.forEach((im) {
        if ((im.reflectee is Tag) && im.reflectee.name == name) {
          res.add(dm);
        }
      });
    });
  });
  return res;
}

@Tag(#foo)
printa() => print('a');

@Tag(#foo)
printb() => print('b');


void main() {
  getMirrorsByTag(#foo).forEach((MethodMirror me) {
    LibraryMirror owner = me.owner;
    owner.invoke(me.simpleName, []);
  });
}


来源:https://stackoverflow.com/questions/26826521/executing-bundle-of-functions-by-their-metadata-tag-in-dart-lang

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