9

How would I do the Dart equivalent of this Java code?

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

(From Jeff Gardner)

4

3 回答 3

8

飞镖代码:

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

从此文档了解更多信息:http ://www.dartlang.org/articles/reflection-with-mirrors/

(来自吉拉德布拉查)

于 2013-06-19T00:26:38.910 回答
0

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

下面是一个简单的例子,它也处理空值并接受 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});

再一次,这在整个项目中克隆是简单而乏味的,但它适用于简单的情况。

于 2019-04-16T12:05:44.260 回答
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}");
}
于 2018-02-06T18:22:55.980 回答