Dart code:

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

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

Using the function name as a string, "hello", is it possible to get the parameter String name of the real function hello ?

有帮助吗?

解决方案

You can use mirrors to do that.

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

其他提示

You get this information through reflection (which it is not yet fully completed):

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);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top