我希望能够做到这样的事情:
class MyClass() {...}
var class_name = "MyClass"; // user input here
new class_name(); // so here, class_name is supposed to be a class constant
有人能提出一个简单的方法吗?
答案 0 :(得分:3)
一种方法是:
library my_library;
import 'dart:mirrors';
void main() {
var userInput = 'MyClass';
var symbol = new Symbol(userInput);
var myClasses = currentMirrorSystem().findLibrary(#my_library).declarations.values.where((dm) => dm is ClassMirror);
var cm = myClasses.firstWhere((cm) => cm.simpleName == symbol);
var instance = cm.newInstance(const Symbol(''), []).reflectee;
}
class MyClass {}
如果你编译成JS,你也应该考虑使用@MirrorsUsed
,否则生成的JS的大小会非常大。