且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何测试Dart中函数的存在?

更新时间:2023-11-03 20:01:22

您可以使用视角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.