Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@interface default declaration usage in Java

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 ) :P

I knew I should've read that document years ago!!!... let's see...

Many APIs require a fair amount of boilerplate code. For....

like image 319
OscarRyz Avatar asked Feb 25 '09 21:02

OscarRyz


1 Answers

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.

like image 89
Michael Myers Avatar answered Oct 12 '22 01:10

Michael Myers