Annotations vs Documentation Comments in Java
Before discussing when to use annotations instead of comments, it's important to understand first what annotations are and what all are they used for in Java. You may like to read this article in case you're not already aware of this - Annotations and their uses in Java >>
Annotations are not a replacement for Documentation comments (they have their own other uses), but in many of the cases (especially in the cases where we need similar structured comments) they are preferred over comments. The reason is that annotations are types in Java - just like any other user defined data type. And hence they can be used once they have been defined.
Annotations in Java are actually a form of interfaces only and hence the definition of an annotation type resembles to that of an interface. The keyword 'interface' is preceded by the symbol '@' in an annotation definition.
A typical documentation comment is what normally apprears in the beginning of any class definition. It's contains author name, version, date, last modified date, etc. So, a sample comment would be something like:-
/**Author: Geek
*Version: 1.0
*Date: 6/16/2008
*Last Modified Date: 6/16/2008
*...
*...
*/
class ClassName{
...
}
For the same purpose, we can define an annotation type as:-
@interface ClassHeaderAnnotation{
String author();
double version() default 1.0;
String date();
String lastModifiedDate();
......
}
Once, an annotation type has been defined, it can used as:-
@Documented // to include this info in the Javadoc
@ClassHeaderAnnotation(
author = "Geek",
version = "1.1", // or just leave this to have the default value
date = "6/16/2008",
lastModifiedDate = "6/16/2008",
......
)
class ClassName{
...
}
If we want to include the annotation in the Javadoc, we need to precede the annotation with another annotation called '@Documented'.
Monday, June 16, 2008
Annotations vs Documentation Comments in Java
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment