有没有一种方法可以在Dart中测试函数或方法的存在而不必尝试调用它并捕获NoSuchMethodError错误?
我正在寻找像以下这样的东西
if (exists("func_name")){...}
测试func_name
函数是否存在。
if (exists("func_name")){...}
测试func_name
函数是否存在。
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
。