如何在Dart中动态(从字符串)获取类名,然后创建一个实例? [英] How to get a Class name dynamically (from a string) in Dart, then create an instance?
本文介绍了如何在Dart中动态(从字符串)获取类名,然后创建一个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想能够做这样的事情:
I would like to be able to do something like this:
class MyClass() {...}
var class_name = "MyClass"; // user input here
new class_name(); // so here, class_name is supposed to be a class constant
任何人都可以建议一个简单的方法
Can anybody suggest a simple way to do it?
推荐答案
一种方法是:
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的大小会非常大。
If you compile to JS, you should also look into using @MirrorsUsed
otherwise the size of the generated JS will be quite large.
这篇关于如何在Dart中动态(从字符串)获取类名,然后创建一个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文