在Dart lang中创建注释

时间:2019-11-21 13:49:27

标签: flutter dart

我要在课程属性中创建一个注释。 示例:

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

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

我尝试使用 reflection ,但是我没有找到元数据,有人知道吗?

1 个答案:

答案 0 :(得分:0)

我更好地理解了dart-lang反射,从而解决了这个问题。基本上,通过反射可以得到对象的引用,该对象包含元数据以及变量和Class方法的值。 这是我查找类属性元数据的示例。

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;
}