2014-11-08 61 views
3

任何人都可以解釋在Dart中使用註釋嗎?dart lang中的自定義註釋/元數據

在文檔,我發現這個例子:

library todo; 

class todo { 
    final String who; 
    final String what; 

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

其次

import 'todo.dart'; 

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

所以,我拿什麼主write()方法來獲得執行DoSomething的()函數?

感謝

回答

2

喜歡的東西

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, []); 
     }; 
     }); 
    }); 
    }); 
} 
+1

我肯定在尋找這樣的事情。謝謝! – Fallenreaper 2016-09-21 21:24:29

+0

如果代碼在瀏覽器中運行,則應考慮使用可反射的包來獲取代碼大小的原因。 – 2016-09-22 05:12:17