2015-11-03 21 views
2

我想獲得動態類名稱的屬性(也試圖實例化它)但接下來的代碼不起作用,因爲我認爲我需要導入具有該類的dart文件在這裏我想反映在文件中的代碼:反映非導入類

//I import the file in other Dart file 
import 'MyClass.dart'; //This only have a class named MyClass with some properties 
import 'OtherClass.dart' 

class mainClass { 
    void mainFunction() { 
    var properties = OtherClass.getProperties('MyClass'); 
    } 
} 

這裏是OtherClass內容:

import "dart:mirrors"; 

class OtherClass { 
    static getProperties (String className) { 
    ClassMirror cm = reflectClass(className); 
    for (var m in cm.declarations.values) 
     print(MirrorSystem.getName(m.simpleName)); 
    } 
} 

反正是有反映的不是實際的飛鏢文件中導入一個類?

希望這是有道理的,在此先感謝。

回答

2

您需要先找到包含該類的庫。使用currentMirrorSystem().libraries來獲取應用程序中導入的所有庫。如果您想避免消除歧義,請將唯一的庫聲明添加到庫中,並將庫名稱傳遞給getProperties()以進行精確查找。

import "dart:mirrors"; 

class OtherClass { 
    static getProperties(String className) { 
    var classSymbol = new Symbol(className); 
    var libs = currentMirrorSystem().libraries; 
    var foundLibs = libs.keys.where((lm) => 
     libs[lm].declarations.containsKey(classSymbol) && 
      libs[lm].declarations[classSymbol] is ClassMirror); 
    if (foundLibs.length != 1) { 
     throw 'None or more than one library containing "${className}" class found'; 
    } 
    ClassMirror cm = libs[foundLibs.first].declarations[classSymbol]; 
    for (var m 
     in cm.declarations.values) print(MirrorSystem.getName(m.simpleName)); 
    } 
} 
+1

Günther說什麼。另外,我建議將該類的名稱作爲符號傳遞,而不是字符串。 – lrn