3

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?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
orion3
  • 9,797
  • 14
  • 67
  • 93
  • 1
    This question was asked one day ago... – Fox32 Nov 16 '13 at 20:21
  • possible duplicate of [Instantiate a class from a string](http://stackoverflow.com/questions/14242712/instantiate-a-class-from-a-string) – Fox32 Nov 16 '13 at 20:21
  • The question is a duplicate, but the answer won't work anymore. Too many changes since January. – Dennis Kaselow Nov 16 '13 at 20:28
  • How about updating the old question instead of creating a new one? So other user don't try to use the non working awnser? – Fox32 Nov 16 '13 at 21:01

1 Answers1

3

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.

Dennis Kaselow
  • 4,351
  • 1
  • 19
  • 18