Nathan Branco
Nathan Branco

Reputation: 11

Create an Annotation in Dart lang

I want create an annotation in class property. Example:

class Annotation {
        const Annotation(this.prop)
        final String prop;
    }

class Model{
    @Annotation("int_prop")
    Int prop;
}

I tried use reflection but I not found the metadata, some one with an idea?

Upvotes: 0

Views: 2450

Answers (1)

Nathan Branco
Nathan Branco

Reputation: 11

I solved the problem understanding better the dart-lang reflection. Basically with reflection you have a reference of Object contains the metadata and value of variables and methods of Class. This is my example to find the metadata of a class property.

import 'dart:mirrors';

void main(List<String> args) {
  Model model = Model(prop: "property value");

  InstanceMirror mirror = reflect(model);

  // this is Map<Symbol,DeclarationMirror> contains properties (VariableMirrors) ,constructors and methods (MethodMirror) of
  // a Model mirror instance
  var mirrorDeclarations = mirror.type.declarations;

  mirrorDeclarations.forEach((symbol, member) {
    if (member is VariableMirror) {
      print("A List of Instance Mirror of Annotation ${member.metadata}");
      // result:A List of Instance Mirror of Annotation [InstanceMirror on Instance of 'Annotation']

      //find a specific metadata
      InstanceMirror annotation = member.metadata.firstWhere(
          (mirror) => mirror.type.simpleName == #Annotation,
          orElse: () => null);
      print("the Instance Mirror of Annotation ${annotation}");
      //result: the Instance Mirror of Annotation InstanceMirror on Instance of 'Annotation'

      //get reflectee, property value, using a Symbol
      print(
          "Annotation param value = ${annotation.getField(#param).reflectee}");
    }
    //result: Annotation param value = value example
  });
}

// simple annotation class
class Annotation {
  const Annotation({this.param});
  final String param;
}

//class property using annotation
class Model {
  Model({this.prop = ""});

  @Annotation(param: "value example")
  final String prop;
}

Upvotes: 1

Related Questions