【问题标题】:How can I get a constructor's parameters via reflection in Dart?如何通过 Dart 中的反射获取构造函数的参数?
【发布时间】:2014-05-19 03:13:12
【问题描述】:

我在 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));
  });
}

【问题讨论】:

    标签: dart dart-mirrors


    【解决方案1】:

    首先,您需要在declarations map 中找到构造函数。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-05
      • 2019-11-23
      • 2011-02-13
      • 1970-01-01
      • 2020-10-06
      • 2021-05-13
      • 2021-10-09
      • 2018-03-26
      相关资源
      最近更新 更多