从Dart中的String创建对象的实例?

时间:2013-06-19 00:26:39

标签: dart dart-mirrors

我如何处理这个Java代码的Dart等价物?

Class<?> c = Class.forName("mypackage.MyClass");
Constructor<?> cons = c.getConstructor(String.class);
Object object = cons.newInstance("MyAttributeValue");

(来自Jeff Gardner)

3 个答案:

答案 0 :(得分:6)

Dart代码:

ClassMirror c = reflectClass(MyClass);
InstanceMirror im = c.newInstance(const Symbol(''), ['MyAttributeValue']);
var o = im.reflectee;

从此文档中了解详情:http://www.dartlang.org/articles/reflection-with-mirrors/

(来自Gilad Bracha)

答案 1 :(得分:0)

使用built_mirrors,您可以采取下一种方式:

library my_lib;

import 'package:built_mirrors/built_mirrors.dart';

part 'my_lib.g.dart';

@reflectable
class MyClass {

  String myAttribute;

  MyClass(this.myAttribute);
}

main() {
  _initMirrors();

  ClassMirror cm = reflectType(MyClass);

  var o = cm.constructors[''](['MyAttributeValue']);

  print("o.myAttribute: ${o.myattribute}");
}

答案 2 :(得分:0)

这个问题困扰着我,直到我发现我可以实现一个粗俗的 from 方法来处理编码的Json对象/字符串 Dart Maps 到所需的类。

下面是一个简单的示例,该示例还处理null并接受JSON(作为 字符串 参数

import 'dart:convert';

class PaymentDetail
{
  String AccountNumber;
  double Amount;
  int ChargeTypeID;
  String CustomerNames;

  PaymentDetail({
    this.AccountNumber,
    this.Amount,
    this.ChargeTypeID,
    this.CustomerNames
  });

  PaymentDetail from ({ string : String, object : Map  }) {
     var map   = (object==null) ? (string==null) ? Map() : json.decode(string) : (object==null) ? Map() : object;
     return new PaymentDetail(
        AccountNumber             : map["AccountNumber"] as String,
        Amount                    : map["Amount"] as double,
        ChargeTypeID              : map["ChargeTypeID"] as int,
        CustomerNames             : map["CustomerNames"] as String
     );
  }

}

下面是实现

 PaymentDetail payDetail =  new PaymentDetail().from(object: new Map());

 PaymentDetail otherPayDetail =  new PaymentDetail().from(object: {"AccountNumber": "1234", "Amount": 567.2980908});

再一次,在整个项目中进行克隆都是很简单和繁琐的,但是适用于简单的情况。