2014-06-27 55 views
1

我有這樣的註解被註解爲它對於具有註釋

class Target{ 
    final String value; 
    const Target(this.value); 
} 

和2班的所有課程獲得ClassMirror實例

@Target("/313") 
class c1{ 

} 

@Target("/314") 
class c2{ 

} 

我怎樣才能得到ClassMirror實例的列表對於具有Target註解的類?

根據所選擇的答案是,如果我知道在

var mirrorSystem = currentMirrorSystem(); 
    var libraryMirror = mirrorSystem.findLibrary(#testlib); 
    for(ClassMirror classMirror in libraryMirror.declarations.values){ 
    if(classMirror.metadata!=null){ 
     for(var meta in classMirror.metadata){ 
      if(meta.type == reflectClass(Path)){ 
       print(classMirror.simpleName); 
       print(meta.getField(#value)); 
      } 
      } 
    } 
    } 
+2

http://stackoverflow.com/questions/24111378/refer-classes-by-their-metadata-tag – JAre

+1

@JAre感謝您添加鏈接。我知道我最近看到了類似的問題,但無法找到它。 –

回答

4

這是什麼庫中存在我的calsses搜索類被註解爲@Target('/313')

@MirrorsUsed(metaTargets: Target) // might be necessary when you build this code to JavaScript 
import 'dart:mirrors'; 

class Target { 
    final String id; 
    const Target(this.id); 
} 

@Target('/313') 
class c1{ 

} 

@Target('/314') 
class c2{ 

} 

@Target('/313') 
@Target('/314') 
class c3{ 

} 

void main() { 
    MirrorSystem mirrorSystem = currentMirrorSystem(); 
    mirrorSystem.libraries.forEach((lk, l) { 
    l.declarations.forEach((dk, d) { 
     if(d is ClassMirror) { 
     ClassMirror cm = d as ClassMirror; 
     cm.metadata.forEach((md) { 
      InstanceMirror metadata = md as InstanceMirror; 
      if(metadata.type == reflectClass(Target) && metadata.getField(#id).reflectee == '/313') { 
      print('found: ${cm.simpleName}'); 
      } 
     }); 
     } 
    }); 
    }); 
} 
當前隔離所有庫

found:Symbol(「c3」)
found:Symbol(「c1」)

+0

我認爲你可以用MirrorsUsed(metaTargets:Target)對其進行優化# – JAre

+0

@J我不需要它,因爲代碼是在服務器上運行的 – FPGA

+0

@FPGA它可能會加快速度或者什麼都不做。沒有傷害:) – JAre