I'm playing around with the mirrors stuff in Dart. I can't find any way reflect a class and figure out if it has a constructor and, if so, what the parameters to this constructor are.
With the ClassMirror, it looks like the "declarations" collection of DeclarationMirror objects will include an entry for the constructor, but there's no way with a DeclarationMirror to tell if whether or not it's a constructor, and no way to see information about the parameters.
With the "instanceMembers" collection of MethodMirror objects, it looks like constructors are not even included. I assume this is because a constructor isn't a normal kind of method that one could invoke, but still, it's odd since MethodMirror has an "isConstructor" attribute.
Is there any way to, given an object type, figure out if it has a constructor and, if so, get information on the parameters to that constructor?
The below code illustrates the problem:
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));
});
}
Firstly, you need to find contructors in declarations
map.
ClassMirror mirror = reflectClass(Person);
List<DeclarationMirror> constructors = new List.from(
mirror.declarations.values.where((declare) {
return declare is MethodMirror && declare.isConstructor;
})
);
Then, you can cast DeclarationMirror
into MethodMirror
and use getter MethodMirror.parameters
to get all parameters of the constructor. Something like:
constructors.forEach((construtor) {
if (constructor is MethodMirror) {
List<ParameterMirror> parameters = constructor.parameters;
}
});