能否提供一个示例,说明如何获取给定类(class)中的所有字段?

例如:

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

最佳答案

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

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

关于dart - DART查找类中的所有字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53917890/

10-08 21:00