How to get a Class name dynamically (from a string) in Dart, then create an instance?

时光毁灭记忆、已成空白 提交于 2019-12-12 10:10:15

问题


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?


回答1:


One way to do it, is:

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 {}

If you compile to JS, you should also look into using @MirrorsUsed otherwise the size of the generated JS will be quite large.



来源:https://stackoverflow.com/questions/20023087/how-to-get-a-class-name-dynamically-from-a-string-in-dart-then-create-an-inst

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!