You have just written an annotation.
Regarding the default
statement in particular: This is used because annotations and interfaces can't have constructors, so this is the only way to have a default value for an annotation attribute. From the 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).
I note that none of the annotations in java.lang.annotation use default values, though.
Usage: You have an annotation @HelloWorld
with an attribute sayHello
. You could put it on a class like this:
@HelloWorld(sayHello="Hi")
public class MyClass {
}
Since you have a default value, you could just put
@HelloWorld
public class MyClass {
}
(Note that the document says, "In annotations with a single element, the element should be named value
"; I believe the only reason to do this is that you could just write @HelloWorld("Hi")
without having to name the parameter.)
As written, your annotation can be used on any valid program element (including methods and variable declarations). You can change this with the @Target
annotation.
Finally, setting the RetentionPolicy
lets you decide if the annotation should be discarded by the compiler, discarded by the VM, or kept always.
Two packages that might also be interesting: javax.annotation and javax.annotation.processing. And here is an example of using annotation processing for source code analysis.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…