在dart中是否可以从字符串中实例化一个类?
例如:
var myObject = window[classNameString];
id myclass = [[NSClassFromString(@"MyClass") alloc] init];
答案 0 :(得分:4)
您需要知道库名称和类名才能使其正常工作。假设您知道两者,下面的示例将实例化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();
});
}
关于此解决方案的一些注意事项:
答案 1 :(得分:4)
语法已更改。 我得到了这样的工作
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'的库,那么这将失败。
答案 2 :(得分:1)
尝试:
Map models = {"Player": Player.instatiate};
var player = models["Player"]();
class Player{
static instatiate() => Player();
}
答案 3 :(得分: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});
再一次,在整个项目中进行克隆都是很简单和繁琐的,但是适用于简单的情况。