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

Sea*_*ean 1 dart dart-mirrors

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

使用ClassMirror,看起来StatementMirror对象的"声明"集合将包含构造函数的条目,但是没有办法使用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));
  });
}
Run Code Online (Sandbox Code Playgroud)

lon*_*luc 5

首先,您需要在declarations地图中找到构造函数.

ClassMirror mirror = reflectClass(Person);

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

然后,您可以DeclarationMirror转换MethodMirror并使用getter MethodMirror.parameters来获取构造函数的所有参数.就像是:

constructors.forEach((construtor) {
  if (constructor is MethodMirror) {
    List<ParameterMirror> parameters = constructor.parameters;
  }
});
Run Code Online (Sandbox Code Playgroud)