dart mirror


import 'dart:mirrors';

class Dt{
  String c = "";
  Dt.fromJson(Map data) {

  }
}


class Test{
  final k = 0;
  Dt d ;
  int a = 1;
  double b = 2;

  String e ;
  bool f;
  List g;
  Test();
  Test.fromJson(Map data){
    InstanceMirror thisMirror = reflect(this);
    ClassMirror dataClassMirror = thisMirror.type;
    dataClassMirror.declarations.forEach((simpleName, fieldClassMirror){

      //判断是否为非静态非常量的属性。(排除方法)
      if(fieldClassMirror is VariableMirror && !fieldClassMirror.isStatic&&!fieldClassMirror.isConst&&!fieldClassMirror.isFinal){
        //获取属性的参数名
        var displayName = MirrorSystem.getName(simpleName);
        //data 数据是否包含该参数名
        if(data.containsKey(displayName)) {
          //获取data数据需要设置的值
          var setValue = data[displayName];
          //类型相同直接赋值
          if(fieldClassMirror.type is ClassMirror) {
            print(" field ${fieldClassMirror.type} value${reflectClass(setValue.runtimeType)}");
            print(" field ${fieldClassMirror.type is int}");
            if(reflectClass(setValue.runtimeType) == fieldClassMirror.type){
              //设置值
              thisMirror.setField(simpleName, setValue);
            }else if(setValue is Map) {
              //初始化构造函数,设置值
              thisMirror.setField(simpleName,
                  (fieldClassMirror.type as ClassMirror).newInstance(Symbol("fromJson"), [setValue]).reflectee);
            }

          }

        }
      }

    });

  }

}

void main() {
  var t1 = Test.fromJson({'a':5,'b':2.0, 'e':'e', 'd':{'c':'test', 'd':1}, 'h':{'c':1, 'd':'2'}, 'g':['a', 'b'], 'k':1});
  print(t1.d == null);
  print(t1.g);

}

转载于:https://my.oschina.net/zdglf/blog/3082623

你可能感兴趣的:(dart mirror)