dartdart-mirrors

Dart create class instance by string with class name


I want to invoke functions of a class by their names inside a string. I know my best option are Mirrors.

var ref = reflect(new TestClass());
ref.invoke(Symbol("test"), []);

It works fine, I can call the function test by a string. But I also want to put "TestClass" inside a string. Is it possible somehow ?

var ref = reflect("TestClass");
ref.invoke(Symbol("test"), []);

Jonas


Solution

  • You can do something like this:

    import 'dart:mirrors';
    
    class MyClass {
      static void myMethod() {
        print('Hello World');
      }
    }
    
    void main() {
      callStaticMethodOnClass('MyClass', 'myMethod'); // Hello World
    }
    
    void callStaticMethodOnClass(String className, String methodName) {
      final classSymbol = Symbol(className);
      final methodSymbol = Symbol(methodName);
    
      (currentMirrorSystem().isolate.rootLibrary.declarations[classSymbol]
              as ClassMirror)
          .invoke(methodSymbol, <dynamic>[]);
    }
    

    Note, that this implementation does require that myMethod is static since we are never creating any object but only operate directly on the class itself. You can create new objects from the class by calling newInstance on the ClassMirror but you will then need to call the constructor.

    But I hope this is enough. If not, please ask and I can try add some more examples.