首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Dart的Mirrors获取对象的所有字段(包括它的超类)?

如何使用Dart的Mirrors获取对象的所有字段(包括它的超类)?
EN

Stack Overflow用户
提问于 2015-02-11 00:25:23
回答 2查看 764关注 0票数 4

给定两个省道类,如:

代码语言:javascript
复制
class A {
  String s;
  int i;
  bool b;
}

class B extends A {
  double d;
}

并给出了B的一个实例

代码语言:javascript
复制
var b = new B();

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-02-11 00:25:23

使用dart:mirrors

代码语言:javascript
复制
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;
  }
}
票数 3
EN

Stack Overflow用户

发布于 2015-02-11 00:29:49

代码语言:javascript
复制
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}");
    }

    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28444437

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档