Skip to content

Instantly share code, notes, and snippets.

@4poc
Created April 17, 2014 04:57
Show Gist options
  • Save 4poc/10953895 to your computer and use it in GitHub Desktop.
Save 4poc/10953895 to your computer and use it in GitHub Desktop.
Use reflection to invoke callbacks in mixins that use metadata as annotation.
@MirrorsUsed(symbols: '', override: '*')
import 'dart:mirrors';
class ReflectionHelper {
static callMethodsByAnnotation(var object, var symbol) {
var mirror = reflectClass(object.runtimeType);
mirror.instanceMembers.forEach((name, method) {
for (var metadata in method.metadata)
if (metadata.hasReflectee && metadata.reflectee == symbol)
reflect(object).invoke(name, []);
});
}
}
class Widget {
static const postPaint = #postPaint;
void paint() {
print('Widget.paint()');
ReflectionHelper.callMethodsByAnnotation(this, postPaint);
}
}
abstract class BorderMixin {
@Widget.postPaint
void paintBorder() {
print('BorderMixin.paintBorder()');
}
}
class TextWidget extends Widget with BorderMixin {
// ...
@override
void paint() {
// ...
print('TextWidget.paint()');
// ...
super.paint();
}
}
void main() {
new TextWidget().paint();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment