【问题标题】:How can i test the existence of a function in Dart?我如何测试 Dart 中函数的存在?
【发布时间】:2012-12-21 17:16:15
【问题描述】:

有没有办法在 Dart 中测试一个函数或方法的存在而不试图调用它并捕获 NoSuchMethodError 错误? 我正在寻找类似的东西

if (exists("func_name")){...}

测试一个名为func_name的函数是否存在。 提前致谢!

【问题讨论】:

    标签: dart dart-mirrors


    【解决方案1】:

    您可以通过 mirrors API 做到这一点:

    import 'dart:mirrors';
    
    class Test {
      method1() => "hello";
    }
    
    main() {
      print(existsFunction("main")); // true
      print(existsFunction("main1")); // false
      print(existsMethodOnObject(new Test(), "method1")); // true
      print(existsMethodOnObject(new Test(), "method2")); // false
    }
    
    bool existsFunction(String functionName) => currentMirrorSystem().isolate
        .rootLibrary.functions.containsKey(functionName);
    
    bool existsMethodOnObject(Object o, String method) => reflect(o).type.methods
        .containsKey(method);
    

    existsFunction 仅测试当前库中是否存在带有functionName 的函数。因此,import 语句中可用的函数existsFunction 将返回false

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多