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;
1

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

My code inspector also keeps warning me: "The method 'newInstance' is not defined for the class 'DeclarationMirror'", but the code works as expected anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.