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

2019-06-23 22:52发布

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 ?

2条回答
冷血范
2楼-- · 2019-06-23 23:02

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.

查看更多
再贱就再见
3楼-- · 2019-06-23 23:07

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   
查看更多
登录 后发表回答