1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.