Attribute is a special class type which provides the ability to define meta-data for other ordinary types. Attribute inherits Object, but cannot be instantiated directly by 'new' operator. Its use is strictly limited at certain prescribed sites at class and member definition.
An attribute can contain zero or more fields:attribute Copyright {
string name;
int year;
}
And it's used with annotation syntax when defining other types:[Copyright(name = "James Kucan", year=2010)]
class ServiceModel {
[Copyright(name = "Larson J. Fisher", year=2011)]
void report(){
}
}
The usage of attributes, such as use-site and repeatability, can be controlled by meta-attribute.
Since attributes are initialized during type loading, only a small subset of types can be used, either as type of an attribute member, or referenced through an initializer. The allowed types include all primitive types, module-less Object types such as Object and String, as well as all Enum types including those defined by users. Also, despite being not an Enum, System.AttributeTarget is also allowed. One-dimensional arrays of any of allowed scalar types are allowed too. All the other types, whether from the system (System.*
) or defined by a user, are denied access in an attribute source context, either at definition or in initializer. Attempts to use such types will result in exceptions faulting type loading.attribute MyAttribute {
string[] name; // OK: one-dimensional array of allowed scalar type is also allowed.
Object[][] objs; // ERROR: multi-dimensional arrays are not allowed.
}
[MyAttribute(name = (new NameBuilder()).getName())] // ERROR: attmpet to use disallowed types in initializer.
class MyObject {
}
Attributes can be retrieved during runtime through reflection API. For more detailed description on Attribute, see tutorial on Attribute.
Parent Class
See Also