如何在Dart中测试函数是否存在?

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

测试func_name函数是否存在。

1个回答

7
你可以使用镜像API来实现这一点: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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接