本文介绍了如何检索Dartlang中的元数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Dartlang教程介绍程序包:meta

Dartlang tutorial introduces package:metahttps://www.dartlang.org/docs/dart-up-and-running/contents/ch02.html#ch02-metadata

DartEditor识别元数据,如上面的教程所示。本教程还解释了如何创建自定义元数据并检索它。

DartEditor recognise the metadata as shown at above tutorial. The tutorial also explains how to create custom metadata and retrieve it. But there is no code sample on how to retrieve it.

推荐答案

通过阅读一些实现,例如Polymer.dart中的@published元数据,我找到方法。

Through reading some implementations such as @published metadata in Polymer.dart, I find the way. https://www.dartlang.org/articles/reflection-with-mirrors/https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-mirrors#id_reflect

以下是示例代码。

import 'dart:mirrors';

class todo {
  final String who;
  final String what;

  const todo(this.who, this.what);
}

@todo('akira', 'add something')
class Foo {
  @todo('naoto', 'do something')
  String fooVariable = 'a';

  @todo('kitano', 'change the name')
  void fooMethod() {

  }
}

void main() {
  InstanceMirror im = reflect(new Foo());
  ClassMirror classMirror = im.type;

  // ClassMirror
  classMirror.metadata.forEach((metadata) {
    print(metadata.reflectee.who); // -> akira
    print(metadata.reflectee.what); // -> add something
  });

  // VariableMirror   
  for (VariableMirror variable in classMirror.variables.values) {
    print(variable.metadata.first.reflectee.who); // -> naoto
    print(variable.metadata.first.reflectee.what); // -> do something
  }

  // MethodMirror
  classMirror.methods.values.forEach((MethodMirror method) {
    print(method.metadata.first.reflectee.who); // -> kitano
    print(method.metadata.first.reflectee.what); // -> change the name
  });
}

这篇关于如何检索Dartlang中的元数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 13:20