dartdart-mirrors

Create an instance of an object from a String in Dart?


How would I do the Dart equivalent of this Java code?

Class<?> c = Class.forName("mypackage.MyClass");
Constructor<?> cons = c.getConstructor(String.class);
Object object = cons.newInstance("MyAttributeValue");

(From Jeff Gardner)


Solution

  • The Dart code:

    ClassMirror c = reflectClass(MyClass);
    InstanceMirror im = c.newInstance(const Symbol(''), ['MyAttributeValue']);
    var o = im.reflectee;
    

    Learn more from this doc: http://www.dartlang.org/articles/reflection-with-mirrors/

    (From Gilad Bracha)