Search code examples
dartdart-mirrors

Dart - class exists from string - class instance from string


I was wondering if it is possible to find out whether a class (in the same library) exists by name (String) and also if it is possible to create an instance of a class from a name (String).

In PHP you can do it like:

$className = 'SomeClass';
if (class_exists($className))
    $instance = new $className;

Solution

  • I would do it more like

    import 'dart:mirrors';
    
    class SomeClass {}
    
    main() {
      String className = 'SomeClass';
      var instance;
    
      ClassMirror cm = currentMirrorSystem().isolate.rootLibrary.declarations[
          new Symbol(className)];
      if (cm != null) {
        instance = cm.newInstance(new Symbol(''), []).reflectee;
      }
      print(instance);
    }