How do I get a MethodMirror for the current function

Issue

Say I have

class RestSimulator {

@Path("/var")
void functionOne() {
  final Type type = this.runtimeType;
  final InstanceMirror instanceMirror = reflect(this);
  final ClassMirror classMirror = instanceMirror.type; 

  final MethodMirror methodMirror = ?????
  var metadata = methodMirror.metadata;
  var path = metadata.first.reflectee;

  print(path.toString()):
  }
}

How can I get the MethodMirror for the calling function???

[Update]
I meant without doing something like

final MethodMirror methodMirror = functions[const Symbol('functionOne')];

So probably the main question is: How do I get the Symbol for the calling / current function?

Solution

AFAIK there’s no simple way to get a reference on the current function at runtime.

I say simple because you can get the name from a StackTrace but it’s really ugly and has horrible performances…

class A {
  m() {
    var functionName;
    try {
      throw '';
    } catch(e, s) {
      functionName = parseStackTraceToGetMethod(s.toString());
    }
    print(functionName); // displays A.m
  }
}
parseStackTraceToGetMethod(String s) =>
  s.substring(8, s.indexOf("("));

main() {
  new A().m();
}

Answered By – Alexandre Ardhuin

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *