如果我知道函数的名称,是否可以获取其参数?

时间:2013-07-09 17:02:32

标签: reflection dart dart-mirrors

飞镖码:

void hello(String name) {
    print(name);
}

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

将函数名称用作字符串"hello",是否可以获取实数函数String name的参数hello

2 个答案:

答案 0 :(得分:4)

您可以使用mirrors来执行此操作。

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");
  }
}

答案 1 :(得分:2)

您通过反思获得此信息(尚未完全完成):

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);
}