Reputation: 469
Using the dart:mirrors library how can I find all corresponding getters and setters for any class mirror.
class Person {
String _name;
Person(this._name);
String get name => _name;
set name (String value) {_name = value;}
}
In this example I'd like to find "name" setter and getter methods to group them without any prior knowledge about the class.
Is there a way to do this properly? Or should I hack my way through using class mirror's instanceMembers, perhaps converting setters symbols to strings or something like that?
Upvotes: 2
Views: 196
Reputation: 5662
you can list getters and setters like this:
import 'dart:mirrors';
class Person {
String _name;
Person(this._name);
String get name => _name;
set name (String value) {_name = value;}
void bar() {
}
}
void main() {
ClassMirror mirror = reflectClass(Person);
mirror.declarations.forEach((Symbol symbol, DeclarationMirror declaration) {
if(declaration is MethodMirror) {
if(declaration.isSetter) {
print('setter: ' + MirrorSystem.getName(declaration.simpleName));
}
if(declaration.isGetter) {
print('getter: ' + MirrorSystem.getName(declaration.simpleName));
}
}
});
}
Output:
getter: name
setter: name=
Is that what you need? I don't think you can do it in a different way.
I don't think you can directly get the variable (_name). You can use declaration.source
to get the source code. maybe you can do some splitting here. :)
Does this help?
Regards, Robert
Upvotes: 3