一些构造可以使用定制的元数据属性化:
Several constructs can be attributed with custom metadata:
- 类和枚举的声明
- 类字段
- 枚举构造函数
- 表达式
- class and enum declarations
- Class fields
- Enum constructors
- Expressions
这些元数据信息可以被在运行时获得,通过 haxe.rtti.Meta API:
These metadata information can be obtained at runtime through the haxe.rtti.Meta API:
import haxe.rtti.Meta;
@author("Nicolas")
@debug
class MyClass {
@range(1, 8)
var value:Int;
@broken
@:noCompletion
static function method() { }
}
class Main {
static public function main() {
// { author : ["Nicolas"], debug : null }
trace(Meta.getType(MyClass));
// [1,8]
trace(Meta.getFields(MyClass).value.range);
// { broken: null }
trace(Meta.getStatics(MyClass).method);
}
}
我们可以简单的识别元数据通过开始的 @ 字符,后跟元数据的名称,和可选的,通过一些逗号分隔的包括在括号中的常量参数。
We can easily identify metadata by the leading @ character, followed by the metadata name and, optionally, by a number of comma-separated constant arguments enclosed in parentheses.
- 类 MyClass 有一个 author 元数据,带有一个单独的String参数“Nicolas”,还有一个 debug 元数据,没有参数。
- 成员变量值有一个 range 元数据,为两个Int参数,1和8.
- 静态method 方法有一个broken元数据,没有参数,还有一个 :noCompletion 元数据,没有参数。
- Class MyClass has an author metadata with a single String argument "Nicolas", as well as a debug metadata without arguments.
- The member variable value has a range metadata with two Int arguments 1 and 8.
- The static method method has a broken metadata without arguments,as well as a :noCompletion metadata without arguments.
main方法访问这些元数据的值可以使用它们的API。输出揭示了获得的数据的结构:
The main method accesses these metadata values using their API. The output reveals the structure of the obtained data:
- 每个元数据都有个字段,字段名是元数据的名称。
- 字段值对应元数据参数。如果没有参数,字段值为 null 。否则字段值是一个数组,每个参数作为一个元素。
- 冒号 : 开头的元数据是省略的。这个类型的元数据作为编译器元数据存在。
- There is a field for each metadata, with the field name being the metadata name.
- The field values correspond to the metadata arguments. If there are no arguments,the field value is null. Otherwise the field value is an array with one element per argument.
- Metadata starting with : is omitted. This kind of metadata is known as compiler metadata.
元数据参数接受的值为:
Allowed values for metadata arguments are:
- 常量(第5.2节)
- 数组声明(第5.5节)(如果所有它们的元素具有资格)
- 对象声明(第5.6节)(如果所有它们的字段值有资格)
- Constants (5.2)
- Arrays declarations (5.5) (if all their elements qualify)
- Object declarations (5.6) (if all their field values qualify)
内建编译器元数据:一个所有定义的元数据详尽的列表可以通过运行 haxe --help-metas 从命令行获取。
Built-in Compiler Metadata An exhaustive list of all defined metadata can be obtained by running haxe --help-metas from command line.
也可以在元数据列表(第8.1节)查看。
See also the Compiler Metadata list (8.1).