1

飞镖代码:

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

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

使用函数名作为字符串,"hello"是否可以得到String name真正函数的参数hello

4

2 回答 2

4

你可以使用镜子来做到这一点。

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");
  }
}
于 2013-07-09T17:34:25.333 回答
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);
}
于 2013-07-09T17:39:49.963 回答