To make a custom annotation in dart is necessary to create a constant object, the following example are valid annotation declarations:
const annotationA = "annotation";
const annotationB = 1;
@annotationA
@annotationB
method() {}
A class with a constant constructor can be use as annotation
class MyAnnotantion {
final String data;
//constan constructor
const MyAnnotantion(this.data);
}
Applying the custom annotation to an example class
@MyAnnotantion('Class')
class Example {
@MyAnnotantion('Property')
String variable;
@MyAnnotantion('Instance method')
instanceMethod(@MyAnnotantion('Instance method parameter') variable) {}
@MyAnnotantion('Static method')
static staticMethod(@MyAnnotantion('Static method parameter') variable) {}
}
@MyAnnotantion('Class')
class Example
final object = Example();
final instanceMirror = reflect(object);
final classMirror = instanceMirror.type;
classMirror.metadata.forEach((metadata) {
print(metadata.reflectee.data);
});
Result: Class
@MyAnnotantion('Property')
String variable;
final object = Example();
final instanceMirror = reflect(object);
final classMirror = instanceMirror.type;
classMirror.declarations.forEach((symbol, declaretion) {
if (declaretion is VariableMirror) {
declaretion.metadata.forEach((metadata) {
print(metadata.reflectee.data);
});
}
});
Result: Property
@MyAnnotantion('Instance method')
instanceMethod(@MyAnnotantion('Instance method parameter') variable) {}
@MyAnnotantion('Static method')
static staticMethod(@MyAnnotantion('Static method parameter') variable) {}
final object = Example();
final instanceMirror = reflect(object);
final classMirror = instanceMirror.type;
classMirror.declarations.forEach((symbol, declaretion) {
if (declaretion is MethodMirror) {
declaretion.metadata.forEach((metadata) {
print(metadata.reflectee.data);
});
}
});
Result: Instance method, Static method
//instanceMethod
@MyAnnotantion('Instance method parameter') variable
//staticMethod
@MyAnnotantion('Static method parameter') variable
final object = Example();
final instanceMirror = reflect(object);
final classMirror = instanceMirror.type;
classMirror.instanceMembers.forEach((symbol, method) {
method.parameters.forEach((parameter) {
parameter.metadata.forEach((metadata) {
print(metadata.reflectee.data);
});
});
});
Result: Instance method parameter, Static method parameter