如果我知道一个函数的名称,有可能得到它的参数吗



飞镖代码:

void hello(String name) {
    print(name);
}
main() {
    var funcName = "hello";
    // how to get the parameter `String name`?
}

使用函数名作为字符串"hello",是否可以获得实际函数hello的参数String name

您可以使用镜像来实现这一点。

import 'dart:mirrors';
void hello(String name) {
    print(name);
}
main() {
  var funcName = "hello";
  // get the top level functions in the current library
  Map<Symbol, MethodMirror> functions = 
      currentMirrorSystem().isolate.rootLibrary.functions;
  MethodMirror func = functions[const Symbol(funcName)];
  // once function is found : get parameters
  List<ParameterMirror> params = func.parameters;
  for (ParameterMirror param in params) {
    String type = MirrorSystem.getName(param.type.simpleName);
    String name = MirrorSystem.getName(param.simpleName);
    //....
    print("$type $name");
  }
}

您通过反射(尚未完全完成)获得这些信息:

library hello_library;
import 'dart:mirrors';
void main() {
  var mirrors =  currentMirrorSystem();
  const libraryName = 'hello_library';
  var libraries = mirrors.findLibrary(const Symbol(libraryName));
  var length = libraries.length;
  if(length == 0) {
    print('Library not found');
  } else if(length > 1) {
    print('Found more than one library');
  } else {
    var method = getStaticMethodInfo(libraries.first, const Symbol('hello'));
    var parameters = getMethodParameters(method);
    if(parameters != null) {
      for(ParameterMirror parameter in parameters) {
        print('name: ${parameter.simpleName}:, type: ${parameter.type.simpleName}');
      }
    }
  }
}
MethodMirror getStaticMethodInfo(LibraryMirror library, Symbol methodName) {
  if(library == null) {
    return null;
  }
  return library.functions[methodName];
}
List<ParameterMirror> getMethodParameters(MethodMirror method) {
  if(method == null) {
    return null;
  }
  return method.parameters;
}
void hello(String name) {
    print(name);
}

相关内容

  • 没有找到相关文章