dart mirror

原创
2019/08/02 14:28
阅读数 48

import 'dart:mirrors';

class Dt{
  String c = "";
  Dt.fromJson(Map<String, dynamic> data) {

  }
}


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

  String e ;
  bool f;
  List<String> g;
  Test();
  Test.fromJson(Map<String, dynamic> 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<String, dynamic>) {
              //初始化构造函数,设置值
              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);

}
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部