dart,如何定义一个类,以便它可以用作类属性?

时间:2014-10-28 11:31:22

标签: dart dart-mirrors

我在Polymer.dart中看到他们有:

class CustomTag {
  final String tagName;
  const CustomTag(this.tagName);
}

但是它如何与其余代码交互?从上面的代码我不知道如何使用@CustomTag('my-tag')实际做什么,但创建一个CustomTag然后垃圾收集,因为没有任何引用它。

1 个答案:

答案 0 :(得分:3)

回答标题中的问题;这些被称为注释;它们只是const构造函数。

回答第二个问题;这些通常用于工具(例如@deprecated)或通过Transformer重写。您可以使用mirrors在运行时访问它们,但对于转换为JavaScript的生产Web应用程序而言,这可能不实用/可行。

这里有一些示例代码taken from this answer

import "dart:mirrors";

void main() {
  var object = new Class1();
  var classMirror = reflectClass(object.runtimeType);
  // Retrieve 'HelloMetadata' for 'object'
  HelloMetadata hello = getAnnotation(classMirror, HelloMetadata);
  print("'HelloMetadata' for object: $hello");

  // Retrieve 'Goodbye' for 'object.method'
  var methodMirror = (reflect(object.method) as ClosureMirror).function;
  Goodbye goodbye = getAnnotation(methodMirror, Goodbye);
  print("'Goodbye' for object: $goodbye");

  // Retrieve all 'Goodbye' for 'object.method'
  List<Goodbye> goodbyes = getAnnotations(methodMirror, Goodbye);
  print("'Goodbye's for object.method': $goodbyes");

  // Retrieve all metadata for 'object.method'
  List all = getAnnotations(methodMirror);
  print("'Metadata for object.method': $all");
}

Object getAnnotation(DeclarationMirror declaration, Type annotation) {
  for (var instance in declaration.metadata) {
    if (instance.hasReflectee) {
      var reflectee = instance.reflectee;
      if (reflectee.runtimeType == annotation) {
        return reflectee;
      }
    }
  }

  return null;
}

List getAnnotations(DeclarationMirror declaration, [Type annotation]) {
  var result = [];
  for (var instance in declaration.metadata) {
    if (instance.hasReflectee) {
      var reflectee = instance.reflectee;
      if (annotation == null) {
        result.add(reflectee);
      } else if (reflectee.runtimeType == annotation) {
        result.add(reflectee);
      }
    }
  }

  return result;
}

@HelloMetadata("Class1")
class Class1 {
  @HelloMetadata("method")
  @Goodbye("method")
  @Goodbye("Class1")
  void method() {
  }
}

class HelloMetadata {
  final String text;
  const HelloMetadata(this.text);
  String toString() => "Hello '$text'";
}

class Goodbye {
  final String text;
  const Goodbye(this.text);
  String toString() => "Goodbye '$text'";
}

输出:

'HelloMetadata' for object: Hello 'Class1'
'Goodbye' for object: Goodbye 'method'
'Goodbye's for object.method': [Goodbye 'method', Goodbye 'Class1']
'Metadata for object.method': [Hello 'method', Goodbye 'method', Goodbye 'Class1']