dart reflection call by String

1.5k views Asked by At

I want to wrote method which call all function in class:

class Example extends MyAbstractClass {
  void f1(){...}
  void f2(){...}
  void f3(){...}
  Example(){
    callAll();//this call f1(), f2() and f3().
  }
}

I have problem in this part of code:

 reflectClass(this.runtimeType).declarations.forEach((Symbol s, DeclarationMirror d) {
  if (d.toString().startsWith("MethodMirror on ")) {
    String methodName = d.toString().substring(16).replaceAll("'", "");
    print(methodName);
    // How to call function by name methodName?
  }
});
2

There are 2 answers

2
Günter Zöchbauer On

instead of

if (d.toString().startsWith("MethodMirror on ")) {

you can use

if (d is MethodMirror) {

You need an InstanceMirror of an instance of the class. I think in your case this would be

var im = reflect(this).invoke(d.simpleName, []); 
im.declarations.forEach((d) ...

see also How can I use Reflection (Mirrors) to access the method names in a Dart Class?

0
Luis Vargas On

Using dson you can do:

library example_lib;

import 'package:dson/dson.dart';

part 'main.g.dart';

@serializable
class Example extends _$ExampleSerializable {
  Example() {
    _callAll();
  }
  fn1() => print('fn1');
  fn2() => print('fn2');
  fn3() => print('fn3');
  fn4() => print('fn4');

  _callAll() {
    reflect(this).methods.forEach((name, method) {
      if(name != '_callAll') this[name]();
    });
  }
}

main(List<String> arguments) {
  _initMirrors();

  new Example();
}