7

我查看了 dart:mirrors 库,发现了 ClassMirror。虽然我看到getField我没有看到对所有领域的访问。不过,我确实看到getters了。

如果我想获得一个类的所有字段,我必须通过getters吗?

4

2 回答 2

6

Zdeslav Vojkovic 的回答有点老了。

截至 2014 年 3 月 2 日,这对我有用,适用于 Dart 1.1.3。

import 'dart:mirrors';

class Test {
    int a = 5;

    static int s = 5;

    final int _b = 6;

    int get b => _b;

    int get c => 0;
}

void main() {

    Test t = new Test();
    InstanceMirror instance_mirror = reflect(t);
    var class_mirror = instance_mirror.type;

    for (var v in class_mirror.declarations.values) {

        var name = MirrorSystem.getName(v.simpleName);

        if (v is VariableMirror) {
            print("Variable: $name => S: ${v.isStatic}, P: ${v.isPrivate}, F: ${v.isFinal}, C: ${v.isConst}");
        } else if (v is MethodMirror) {
            print("Method: $name => S: ${v.isStatic}, P: ${v.isPrivate}, A: ${v.isAbstract}");
        }

    }
}

会输出:

Variable: a => S: false, P: false, F: false, C: false
Variable: s => S: true, P: false, F: false, C: false
Variable: _b => S: false, P: true, F: true, C: false
Method: b => S: false, P: false, A: false
Method: c => S: false, P: false, A: false
Method: Test => S: false, P: false, A: false   
于 2014-03-02T07:14:18.630 回答
4

不,你应该通过ClassMirror.variables

class Test {
  int a = 5;
  static int s = 5;
  final int _b = 6;

  int get b => _b;
  int get c => 0;
}

void main() {
  Test t = new Test();
  InstanceMirror instance_mirror = reflect(t);
  var class_mirror = instance_mirror.type;
  for(var v in class_mirror.variables.values)
  {
    var name = MirrorSystem.getName(v.simpleName);
    print("$name => S: ${v.isStatic}, P: ${v.isPrivate}, F: ${v.isFinal}");
  }
}

这将输出:

_b => S: false, P: true, F: true 
a => S: false, P: false, F: false
s => S: true, P: false, F: false

ClassMirror.getters只会返回bc

于 2013-06-10T12:34:14.340 回答