How do I get all fields for a class in Dart?

99封情书 提交于 2019-12-01 17:09:32

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!