I have just discovered this feature.
Declaring an interface using the ‘@interface’ syntax allows you to put a default value.
public @interface HelloWorld { public String sayHello() default 'hello world'; }
This is something new for me. How is that default value suppose to be used.
I cannot find references to that, because the www is full of java interface documents prior to ‘@’ addition in Java 1.5 ( was it on .5 or in .4? )
EDIT
Thanks for the answers ( I was somehow close to ‘annotation’, for I use the tag already ) 😛
I knew I should’ve read that document years ago!!!… let’s see…
Many APIs require a fair amount of boilerplate code. For….
You have just written an annotation.
Regarding the
defaultstatement 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:I note that none of the annotations in java.lang.annotation use default values, though.
Usage: You have an annotation
@HelloWorldwith an attributesayHello. You could put it on a class like this:Since you have a default value, you could just put
(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
@Targetannotation.Finally, setting the
RetentionPolicylets 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.