annotation_crawler 1.1.0 annotation_crawler: ^1.1.0 copied to clipboard
Helps finding classes or methods with specific annotations.
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({this.act, this.scene});
}
abstract class Play {
final String name;
Play(this.name);
perform();
}
@Author('Arthur Miller')
class MajestyPlay extends Play {
MajestyPlay() : super('Her majesty\'s Theater');
@override
perform() {
performAct1Scene1();
performAct1Scene2();
performAct2Scene1();
}
@Scene(act: 1, scene: 1)
performAct1Scene1() => print('Performing play "$name" act 1 scene 1.');
@Scene(act: 1, scene: 2)
performAct1Scene2() => print('Performing play "$name" act 1 scene 2.');
@Scene(act: 2, scene: 1)
performAct2Scene1() => print('Performing play "$name" act 2 scene 1.');
}
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 ClassMirror playClass = decl.declaration;
final Play play = playClass.newInstance(const Symbol(''), []).reflectee;
play.perform();
});
print('Now playing only act 2 scene 1:');
final majestyPlay = new MajestyPlay();
final declaration = annotatedDeclarations(Scene, on: majestyPlay.runtimeType)
.singleWhere((decl) {
final Scene scene = decl.annotation;
return scene.act == 2 && scene.scene == 1;
});
/// Invoke the found method on given object.
reflect(majestyPlay).invoke(declaration.declaration.simpleName, []);
}