6
有沒有一種方法來測試飛鏢中的函數或方法的存在而不嘗試調用它並捕獲NoSuchMethodError錯誤? 我在尋找類似我如何測試Dart中函數的存在?
if (exists("func_name")){...}
以測試功能是否命名func_name
存在。 在此先感謝!
有沒有一種方法來測試飛鏢中的函數或方法的存在而不嘗試調用它並捕獲NoSuchMethodError錯誤? 我在尋找類似我如何測試Dart中函數的存在?
if (exists("func_name")){...}
以測試功能是否命名func_name
存在。 在此先感謝!
你可以做到這一點與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
。