annotation_crawler 2.0.0
annotation_crawler: ^2.0.0 copied to clipboard
Helps finding classes or methods with specific annotations with the dart mirror system.
import 'dart:mirrors';
import 'package:annotation_crawler/annotation_crawler.dart';
class Author {
final String name;
const Author(this.name);
}
class Scene {
final int act;
final int scene;
const Scene({required this.act, required this.scene});
}
abstract class Play {
final String name;
Play(this.name);
void perform();
}
@Author('Arthur Miller')
class MajestyPlay extends Play {
MajestyPlay() : super('Her majesty\'s Theater');
@override
perform() {
performAct1Scene1();
performAct1Scene2();
performAct2Scene1();
}
@Scene(act: 1, scene: 1)
void performAct1Scene1() => print('Performing play "$name" act 1 scene 1.');
@Scene(act: 1, scene: 2)
void performAct1Scene2() => print('Performing play "$name" act 1 scene 2.');
@Scene(act: 2, scene: 1)
void performAct2Scene1() => print('Performing play "$name" act 2 scene 1.');
}
void main() {
// Perform all plays written by Arthur Miller.
annotatedDeclarations(Author)
.where((decl) =>
decl.declaration is ClassMirror &&
decl.annotation == const Author("Arthur Miller"))
.forEach((decl) {
final playClass = decl.declaration as ClassMirror;
final play =
playClass.newInstance(const Symbol(''), <dynamic>[]).reflectee as Play;
play.perform();
});
print('Now playing only act 2 scene 1:');
final majestyPlay = MajestyPlay();
final declaration = annotatedDeclarations(Scene, on: majestyPlay.runtimeType)
.singleWhere((decl) {
final Scene scene = decl.annotation as Scene;
return scene.act == 2 && scene.scene == 1;
});
/// Invoke the found method on given object.
reflect(majestyPlay).invoke(declaration.declaration.simpleName, <dynamic>[]);
}