我正在尝试获取动态类名称的属性(也尝试实例化它),但是下一个代码不起作用,因为我认为我需要导入在文件中具有类代码的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));
}
}
无论如何,是否反映了未在实际Dart文件中导入的类?
希望这是有道理的,先谢谢。
答案 0 :(得分: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));
}
}