1

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;
Kaspi
  • 3,538
  • 5
  • 24
  • 29

2 Answers2

1

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);
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

In time of posting this answer, the solution is not as straightforward as in PHP, but it can be managed this way:

String className = 'SomeClass';
if (currentMirrorSystem().isolate.rootLibrary.declarations.keys.join('').contains('Symbol("${className}")'))
    var instance = currentMirrorSystem().isolate.rootLibrary.declarations[new Symbol(className)].newInstance(new Symbol(''), []).reflectee;

It's a little bit naughty approach with searching in a string, but it's the simplest way I could make it working by myself.

Next you can call the instance's properties simply:

instance.method();

Hope it helps someone.

Kaspi
  • 3,538
  • 5
  • 24
  • 29
  • My code inspector also keeps warning me: "The method 'newInstance' is not defined for the class 'DeclarationMirror'", but the code works as expected anyway. – Kaspi Nov 10 '15 at 12:49