你刚刚写了一个
annotation。
关于默认语句特别是:这是因为注释和接口不能有构造函数,所以这是唯一的方法来为注释属性有一个默认值。从Java Language Specification:
An annotation type element may have a default value specified for it. This is done by following its (empty) parameter list with the keyword default and the default value of the element.
Defaults are applied dynamically at the time annotations are read; default values are not compiled into annotations. Thus, changing a default value affects annotations even in classes that were compiled before the change was made (presuming these annotations lack an explicit value for the defaulted element).
用法:您有一个带有属性sayHello的注释@HelloWorld。你可以把它放在类如下:
@HelloWorld(sayHello="Hi")
public class MyClass {
}
由于你有一个默认值,你可以放
@HelloWorld
public class MyClass {
}
(请注意,文档说,“在使用单个元素的注释中,元素应该命名为值”;我相信唯一的原因是,您可以只写@HelloWorld(“Hi”)而不必命名参数。)
如所写的,您的注释可以用于任何有效的程序元素(包括方法和变量声明)。您可以使用@Target注释更改此设置。
最后,设置RetentionPolicy允许您决定注释是否应该被编译器丢弃,被VM抛弃或始终保持。