Retrieving getter values with dart:mirrors reflect

2019-07-30 01:25发布

问题:

I have the following code (simplified), that uses reflection to iterate a class's fields and getters and output the values. The ContainsGetter class contains a getter, and the ContainsField class contains a simple field.

Using dart:mirrors library, I can get the value of the field by using instanceMirror.getField(fieldName)), but not the getter by using instanceMirror.invoke(fieldName,[]).

The following Dart script (using the build 17463) gives the output below:

app script

import 'dart:mirrors';

class ContainsGetter { // raises an error
  String get aGetter => "I am a getter";
}

class ContainsField { // works fine
  String aField = "I am a field";
}

void main() {
  printFieldValues(reflect(new ContainsField()));
  printGetterValues(reflect(new ContainsGetter()));
}

void printFieldValues(instanceMirror) {
  var classMirror = instanceMirror.type;
  classMirror.variables.keys.forEach((key) {
    var futureField = instanceMirror.getField(key); // <-- works ok
    futureField.then((imField) => print("Field: $key=${imField.reflectee}"));
  });
}

void printGetterValues(instanceMirror) {
  var classMirror = instanceMirror.type;
  classMirror.getters.keys.forEach((key) {
    var futureValue = instanceMirror.invoke(key,[]); // <-- fails
    futureValue.then((imValue) => print("Field: $key=${imValue.reflectee}"));
  });
}

output

Field: aField=I am a field
Uncaught Error: Compile-time error during mirrored execution: <Dart_Invoke: did not find instance method 'ContainsGetter.aGetter'.>
Stack Trace:
#0      _LocalObjectMirrorImpl._invoke (dart:mirrors-patch:163:3)
#1      _LocalObjectMirrorImpl.invoke (dart:mirrors-patch:125:33)

(An acceptable could be that "this bit just hasn't been written yet!")

回答1:

Aah, I've just worked it out. Although aGetter is like a method in its implementation, you use the getField() rather than invoke to retrieve its value.

void printGetterValues(instanceMirror) {
  var classMirror = instanceMirror.type;
  classMirror.getters.keys.forEach((key) {
    var futureValue = instanceMirror.getField(key); // <-- now works ok
    futureValue.then((imValue) => print("Field: $key=${imValue.reflectee}"));
  });
}