Home > Blockchain >  Dart - Get result from a method invoked using reflection
Dart - Get result from a method invoked using reflection

Time:07-02

I'm trying to use dart's mirror API to dynamically invoke a function.

How can I obtain the result that's returned from the doWork method when invoking it via an InstanceMirror

class MyData {
  String someString;
}

class MyService {
  Future<MyData> doWork() async {
    print('doing work');
    return await Future(() => MyData()..someString = 'my result');
  }
}
void main() async {
  var instance = MyService();
  var mirrror = reflect(instance);
  var result = mirrror.invoke(#doWork, []);
}

I can see that "doing work" gets printed to the console so I know it's being invoked, but I'm struggling to interpret the result from the invoke function.

CodePudding user response:

The value are inside the InstanceMirror in the property reflectee. So something like this:

import 'dart:mirrors';

class MyData {
  String? someString;
}

class MyService {
  Future<MyData> doWork() async {
    print('doing work');
    return await Future(() => MyData()..someString = 'my result');
  }
}
void main() async {
  var instance = MyService();
  var mirrror = reflect(instance);
  var result = mirrror.invoke(#doWork, <dynamic>[]);
  var resultValue = await (result.reflectee as Future<MyData>);
  print(resultValue.someString); // my result
}
  • Related