需要Dart镜像instantiate()函数

时间:2014-01-20 04:52:37

标签: dart dart-mirrors dart-isolates

为我的生活添加一些理智,为Dart的instantiate()库寻找mirror函数作为语法糖:instantiate( class|type|instance, argArray )

class Klass {
  int i1;
  Klass( int i1 ) {
    this.i1 = (i1 is int) ? i1 : 0;
  }
}
type ktype = Klass;
Klass kinstance = new Klass( 5 );

Klass test1 = instantiate( Klass, [5] );
Klass test2 = instantiate( ktype, [5] );
Klass test3 = instantiate( kinstance, [5] );

目前我与mirrors的90%的互动都会被这一功能所覆盖。目前盲目地削减和复制出纯粹的愚蠢。当然比我聪明的人已经做到了!


所有场合都是instantiate( type, [constructor, positional, named] )

  • 构造函数,位置和命名的参数都是可选的
  • 类型可以是Type,实例化类型或类型
  • 的字符串表示形式
  • 构造函数:例如,new Map.from(...) - 'from'是构造函数,'from'或#from
  • 位置:列表中的位置参数
  • named:在Map中命名参数,键可以是'key'或#key
dynamic instantiate( dynamic v_type, [dynamic v_constructorName, List v_positional, Map v_named] ) {
  Type type =
    ( _type is Type ) ? v_type
    : (v_type is String ) ? str2Type( v_type )
    : reflect(v_type).type.reflectedType;
  Map v_named2 =
    (v_named is Map) ? v_named
    : (v_positional is Map) ? v_positional
    : (v_constructorName is Map) ? v_constructorName
    : {};
  Map named = {};
  v_named2.keys.forEach( (k) => named[(k is Symbol)?k:new Symbol(k)] = v_named2[k] );
  List positional =
    (v_positional is List) ? v_positional
    : (v_constructorName is List) ? v_constructorName : [];
  Symbol constructorName =
    (v_constructorName is Symbol) ? v_constructorName
    : (v_constructorName is String) ? Symbol(v_constructorName)
    : const Symbol('');
  return reflectClass(type).newInstance(constructorName, positional, named).reflectee;
}

1 个答案:

答案 0 :(得分:5)

import 'dart:mirrors';

void main() {
  Type ktype = Klass;
  Klass kinstance = new Klass( 5 );
  // Constructor name
  var ctor = const Symbol("");

  Klass test1 = instantiate(Klass, ctor, [1]);
  Klass test2 = instantiate(ktype, ctor, [2]);
  Klass test3 = instantiate(reflect(kinstance).type.reflectedType, ctor, [3]);
  Klass test4 = instantiate(Klass, #fromString, ["4"]);

  print(test1.i1);
  print(test2.i1);
  print(test3.i1);
  print(test4.i1);
}

dynamic instantiate(Type type, Symbol constructorName, List positional, [Map named]) {
  return reflectClass(type).newInstance(constructorName, positional, named).reflectee;
}

class Klass {
  int i1;
  Klass( int i1 ) {
    this.i1 = (i1 is int) ? i1 : 0;
  }

  Klass.fromString(String i) {
    i1 = int.parse(i, onError : (s) => i1 = 0);
  }
}

输出:

1
2
3
4