【问题标题】:How do I get all the fields of an object (including its superclass), using Dart's Mirrors API?如何使用 Dart 的 Mirrors API 获取对象的所有字段(包括其超类)?
【发布时间】:2015-02-11 00:25:23
【问题描述】:

给定两个 Dart 类,例如:

class A {
  String s;
  int i;
  bool b;
}

class B extends A {
  double d;
}

给定一个B的实例:

var b = new B();

如何获取b 实例中的所有字段,包括其超类中的字段?

【问题讨论】:

    标签: dart dart-mirrors


    【解决方案1】:

    使用dart:mirrors

    import 'dart:mirrors';
    
    class A {
      String s;
      int i;
      bool b;
    }
    
    class B extends A {
      double d;
    }
    
    main() {
      var b = new B();
    
      // reflect on the instance
      var instanceMirror = reflect(b);
    
      var type = instanceMirror.type;
    
      // type will be null for Object's superclass
      while (type != null) {
        // if you only care about public fields,
        // check if d.isPrivate != true
        print(type.declarations.values.where((d) => d is VariableMirror));
        type = type.superclass;
      }
    }
    

    【讨论】:

      【解决方案2】:
      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}");
          }
      
          }
      }
      

      【讨论】:

      • 你能更新你的答案来处理超类吗?
      猜你喜欢
      • 2022-12-01
      • 2013-06-05
      • 2017-10-29
      • 1970-01-01
      • 2019-03-11
      • 2020-04-11
      • 2023-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多