在 dart 中是否可以从字符串实例化一个类?
例如:
- javascript中的香草:
var myObject = window[classNameString];
- 目标-C:
id myclass = [[NSClassFromString(@"MyClass") alloc] init];
在 dart 中是否可以从字符串实例化一个类?
例如:
var myObject = window[classNameString];
id myclass = [[NSClassFromString(@"MyClass") alloc] init];
您需要知道库名称和类名称才能使事情正常工作。假设您都知道,下面的示例将实例化TestClass
并调用doStuff
它。
library test;
import "dart:mirrors";
class TestClass {
doStuff() => print("doStuff was called!");
}
main() {
MirrorSystem mirrors = currentMirrorSystem();
LibraryMirror lm = mirrors.libraries['test'];
ClassMirror cm = lm.classes['TestClass'];
Future tcFuture = cm.newInstance('', []);
tcFuture.then((InstanceMirror im) {
var tc = im.reflectee;
tc.doStuff();
});
}
关于此解决方案的一些注意事项:
语法已更改。我让它这样工作
library test;
import "dart:mirrors";
class TestClass {
doStuff() => print("doStuff was called!");
}
main() {
MirrorSystem mirrors = currentMirrorSystem();
LibraryMirror lm = mirrors.libraries.values.firstWhere(
(LibraryMirror lm) => lm.qualifiedName == new Symbol('test'));
ClassMirror cm = lm.declarations[new Symbol('TestClass')];
InstanceMirror im = cm.newInstance(new Symbol(''), []);
var tc = im.reflectee;
tc.doStuff();
}
如果有更多名为“test”的库,这将失败。
尝试:
Map models = {"Player": Player.instatiate};
var player = models["Player"]();
class Player{
static instatiate() => Player();
}
这是一个一直困扰着我的问题,直到我发现我可以实现一个粗略的 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});
再一次,这在整个项目中克隆是简单而乏味的,但它适用于简单的情况。