如何通过Dart中的反射获取构造函数的参数?

时间:2014-05-19 03:13:12

标签: dart dart-mirrors

我正在玩达特的镜子。我找不到任何方式反映一个类,并弄清楚它是否有一个构造函数,如果有的话,这个构造函数的参数是什么。

使用ClassMirror,看起来StatementMirror对象的“declarations”集合将包含构造函数的一个条目,但是StatementMirror无法判断它是否是构造函数,并且无法查看有关的信息。参数。

使用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));
  });
}

1 个答案:

答案 0 :(得分:5)

首先,您需要在declarations地图中找到承包商。

ClassMirror mirror = reflectClass(Person);

List<DeclarationMirror> constructors = new List.from(
  mirror.declarations.values.where((declare) {
    return declare is MethodMirror && declare.isConstructor;
  })
);

然后,您可以将DeclarationMirror转换为MethodMirror并使用getter MethodMirror.parameters来获取构造函数的所有参数。类似的东西:

constructors.forEach((construtor) {
  if (constructor is MethodMirror) {
    List<ParameterMirror> parameters = constructor.parameters;
  }
});
相关问题