我正在玩 Dart 中的镜子东西。我找不到任何方法来反映一个类并弄清楚它是否有构造函数,如果有,这个构造函数的参数是什么。
使用 ClassMirror 时,DeclarationMirror 对象的“声明”集合看起来将包含构造函数的条目,但是 DeclarationMirror 无法判断它是否是构造函数,也无法查看有关参数的信息。
使用 MethodMirror 对象的“instanceMembers”集合,看起来甚至不包括构造函数。我认为这是因为构造函数不是一种可以调用的普通方法,但仍然很奇怪,因为 MethodMirror 具有“isConstructor”属性。
有没有办法,给定一个对象类型,确定它是否有一个构造函数,如果有,获取该构造函数的参数信息?
下面的代码说明了这个问题:
import 'dart:mirrors';
class Person {
String name;
int age;
Person(this.name, this.age);
string getNameAndAge() {
return "${this.name} is ${this.age} years old";
}
}
void main() {
ClassMirror classMirror = reflectClass(Person);
// This will show me the constructor, but a DeclarationMirror doesn't tell me
// anything about the parameters.
print("+ Declarations");
classMirror.declarations.forEach((symbol, declarationMirror) {
print(MirrorSystem.getName(symbol));
});
// This doesn't show me the constructor
print("+ Members");
classMirror.instanceMembers.forEach((symbol, methodMirror) {
print(MirrorSystem.getName(symbol));
});
}