【问题标题】:dart reflection call by StringString 的 dart 反射调用
【发布时间】:2014-11-23 17:04:31
【问题描述】:

我想编写调用类中所有函数的方法:

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

这部分代码有问题:

 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?
  }
});

【问题讨论】:

    标签: dart dart-mirrors


    【解决方案1】:

    而不是

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

    你可以使用

    if (d is MethodMirror) {
    

    您需要一个类实例的InstanceMirror。我认为在你的情况下,这将是

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

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

    【讨论】:

    • 谢谢,你的 if 看起来更好。 MethodMirror 没有方法调用。
    • 你只需要在迭代之前reflect(this)
    【解决方案2】:

    使用dson 你可以做到:

    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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-16
      • 1970-01-01
      • 2015-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-21
      • 1970-01-01
      相关资源
      最近更新 更多