I looked at the dart:mirrors library, and I found ClassMirror. While I saw getField I didn't see access to all fields. I did see getters, though.

If I want to get all fields for a class, do I have to go through getters ?

有帮助吗?

解决方案

Zdeslav Vojkovic's answer is a bit old.

This works for me, for Dart 1.1.3, as of March 2 2014.

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

    }
}

Would output:

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   

其他提示

No, you should go through 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}");
  }
}

This will output:

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

ClassMirror.getters would only return b and c.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top