custom annotation / Metadata in dart lang

爱⌒轻易说出口 提交于 2019-12-06 05:01:06

问题


Can any one explain me the use of annotations in Dart?

In the documentations, I found this example:

library todo;

class todo {
  final String who;
  final String what;

  const todo(this.who, this.what);
}

followed by

import 'todo.dart';

@todo('seth', 'make this do something')
void doSomething() {
 print('do something');
}

so, what shall I write in the main() to get the doSomething() function executed?

thanks


回答1:


Something like

import 'dart:mirrors';
import 'do_something.dart';
import 'todo.dart';


void main() {
  currentMirrorSystem().libraries.forEach((uri, lib) {
    //print('lib: ${uri}');
    lib.declarations.forEach((s, decl) {
      //print('decl: ${s}');
      decl.metadata.where((m) => m.reflectee is Todo).forEach((m) {
        var anno = m.reflectee as Todo;
        if(decl is MethodMirror) {
          print('Todo(${anno.who}, ${anno.what})');
          ((decl as MethodMirror).owner as LibraryMirror).invoke(s, []);
        };
      });
    });
  });
}


来源:https://stackoverflow.com/questions/26821567/custom-annotation-metadata-in-dart-lang

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