如何测试在DART功能的存在?(How can i test the existence of a

2019-08-04 11:44发布

有没有一种方法来测试达特函数或方法的存在,但不尝试调用它,赶上的NoSuchMethodError的错误? 我在寻找类似

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

测试函数命名是否func_name存在。 提前致谢!

Answer 1:

你可以做到这一点与镜子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



文章来源: How can i test the existence of a function in Dart?