gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:10:50 26 4
gpt4 key购买 nike

我在玩Dart中的镜子东西。我找不到任何方法来反射(reflect)类并弄清楚它是否有构造函数,如果有,则确定该构造函数的参数是什么。

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

最佳答案

首先,您需要在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;
}
});

关于dart - 如何在Dart中通过反射获取构造函数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23729201/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com