2

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?

4

1 回答 1

3

您可以像这样列出 getter 和 setter:

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

输出:

getter: name
setter: name=

那是你需要的吗?我认为你不能以不同的方式做到这一点。

我认为您不能直接获取变量(_name)。您可以使用declaration.source来获取源代码。也许你可以在这里做一些拆分。:)

这有帮助吗?

问候,罗伯特

于 2014-05-28T20:09:07.787 回答