I am trying to come up with an example of how we could search for the @override metadata annotation using reflection in Dart.
In the examples I used to learn the dart:mirrors library and reflection, they were always searching for custom made annotations.
Here is an example where they search for a custom "Todo" annotation
When searching for custom made annotations, they would simply compare the metadata's reflectee to the class data type to check for a match.
In Dart's documentation linked below, you can see an example implementation of an _Override instance.
Here is Dart documentation on the override constant
This lead to me to try:
if(meta.reflectee is _Override) {
print('Found!);
}
But the "_Override" cannot be resolved and suggest no imports to access such a data instance.
I am able to toString the reflectee for comparison but I feel like it is a dirty solution:
if (meta.reflectee.toString() == "Instance of '_Override'") {
print('Found!');
}
When using the @override annotation, I am struggling to find a way to compare the metadata's reflectee to the instance type of _Override.
Here is the Dog class:
class Dog extends Animal {
Dog(String name) : super(name);
@override
void makeNoise() {
print('Bark, bark!');
}
}
Here is my reflection search code:
Dog dog = Dog('Harper');
InstanceMirror instanceMirror = reflect(dog);
ClassMirror classMirror = instanceMirror.type;
classMirror.instanceMembers.forEach((_, member) {
print(member.owner.simpleName);
print(member.simpleName);
print(member.isRegularMethod);
member.metadata.forEach((meta) {
print(meta.reflectee);
if (meta.reflectee is _Override) {
print('Found!');
}
});
});
Finally, here is my output when the instanceMembers.forEach loop gets to the method I am interested in:
Symbol("Dog")
Symbol("makeNoise")
true
Instance of '_Override'
Aucun commentaire:
Enregistrer un commentaire