问题
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