DART查找类中的所有字段

时间:2018-12-24 21:44:51

标签: dart

有人可以举一个例子,说明如何获取给定班级中的所有字段吗?

例如:

class A{
  String aa;
  String bb;
  static String ss;
  string simple(){
    return 'simple';
  }
  getallMemberFields(){
   // returun ["aa", "bb"]
 }
}

1 个答案:

答案 0 :(得分:1)

如果您在询问反射,这是一个示例,不仅可以获取变量和函数名称,还可以获取有关它们的一些额外信息

import 'dart:mirrors';

class A {
  String aa;
  String bb;
  static String ss;
  String simple() {
    return 'simple';
  }

  getallMemberFields() {
    // returun ["aa", "bb"]
  }
}

void main() {
  InstanceMirror instance_mirror = reflect(new A());
  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');
      print(
          'Static: ${v.isStatic}, Private: ${v.isPrivate}, Final: ${v.isFinal}, Const: ${v.isConst}');
    } else if (v is MethodMirror) {
      print('Method: $name');
      print(
          'Static: ${v.isStatic}, Private: ${v.isPrivate}, Abstract: ${v.isAbstract}');
    }
  }
}

打印:

Variable: aa
Static: false, Private: false, Final: false, Const: false
Variable: bb
Static: false, Private: false, Final: false, Const: false
Variable: ss
Static: true, Private: false, Final: false, Const: false
Method: simple
Static: false, Private: false, Abstract: false
Method: getallMemberFields
Static: false, Private: false, Abstract: false
Method: A
Static: false, Private: false, Abstract: false