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)
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)
飞镖代码:
ClassMirror c = reflectClass(MyClass);
InstanceMirror im = c.newInstance(const Symbol(''), ['MyAttributeValue']);
var o = im.reflectee;
从此文档了解更多信息:http ://www.dartlang.org/articles/reflection-with-mirrors/
(来自吉拉德布拉查)
这是一个一直困扰着我的问题,直到我发现我可以实现一个粗略的 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});
再一次,这在整个项目中克隆是简单而乏味的,但它适用于简单的情况。
使用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}");
}