How can i test the existence of a function in Dart?

橙三吉。 提交于 2019-12-22 04:53:15

问题


Is there a way to test the existence of a function or method in Dart without trying to call it and catch a NoSuchMethodError error? I am looking for something like

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

to test whether a function namedfunc_nameexists. Thanks in advance!


回答1:


You can do that with 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 only tests if a function with functionName exists in the current library. Thus with functions available by import statement existsFunction will return false.



来源:https://stackoverflow.com/questions/13994443/how-can-i-test-the-existence-of-a-function-in-dart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!