Several constructs can be attributed with custom metadata:
class
and enum
declarationsThese metadata information can be obtained at runtime through the haxe.rtti.Meta
API:
import haxe.rtti.Meta; @author("Nicolas") @:keep class MyClass { @range(1, 8) var value:Int; @broken static function method() {} } class Main { static public function main() { // { author : ["Nicolas"] } 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
has an author
metadata with a single String argument "Nicolas"
, as well as a :keep
metadata without arguments.value
has a range
metadata with two Int arguments 1
and 8
.method
has a broken
metadata without arguments.The main
method accesses these metadata values using their API. The output reveals the structure of the obtained data:
null
. Otherwise the field value is an array with one element per argument.Allowed values for metadata arguments are:
Metadata starting with :
, such as @:keep
, is available at compile time only; it is omitted at runtime. It may be used by macros or by the Haxe compiler itself. Unlike runtime metadata, arguments to compile-time metadata can be any valid expression.
An exhaustive list of all defined metadata can be obtained by running haxe --help-metas
from command line.
Prior to Haxe 4, metadata names had to be valid identifiers. Starting in Haxe 4, metadata names can consist of multiple identifiers separated by .
symbols. This change was primarily intended to make it easier to organize compile-time metadata. Runtime metadata with such a name can only be accessed via dynamic access.