如何测试Dart中函数的存在? [英] How can i test the existence of a function in Dart?
本文介绍了如何测试Dart中函数的存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法测试一个函数或方法在Dart中的存在,而不试图调用它并捕获NoSuchMethodError错误?
我正在寻找像
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")){...}
来测试是否存在名为 func_name
的函数。
提前感谢!
to test whether a function namedfunc_name
exists.
Thanks in advance!
推荐答案
您可以使用视角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
code> functionName 存在于当前库中。因此,通过 import
语句 existsFunction
提供的函数将返回 false
。
existsFunction
only tests if a function with functionName
exists in the current library. Thus with functions available by import
statement existsFunction
will return false
.
这篇关于如何测试Dart中函数的存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文