Collection of references and notes on Java and J2EE

Friday, August 11, 2006

Annotations in Java 1.5

Annotations are metadata used in source code to be interpreted by the tools and libraries without affecting the execution of the program. Annotations can be interpreted at compile-time or run-time. A use of annotation could be, mark a method as deprecated; use of deprecated can then be interpreted by the compiler to generate warnings. Another use could be pass configuration values for the tool to be process, generate or modify configuration files. Annotations are beneficial in documentation, code-analysis and compiler checking.

Example:
@deprecated public void foo(){}

Annotations consist of '@' sign followed by type of annotation and a parenthesized list of name-value pair of elements. Annotations can be used everywhere where other modifiers like public or static can be used. As a convention annotation is preceded by other modifiers.


Declaration of annotation type:
Example: public @interface breaksStandard {
public String reviewer();
public String reviewDate;
public String reason default "";}

Similar to interface declaration, modifier '@' sign prefixed to keyword interface. Return types can only be primitives, String, Class, enums and annotations (and arrays of these).

Usage: @breaksStandard(reviewer="XYZ", reviewDate="Aug 10, 2006") public void FOO(){}

Types:
1. In built annotations -
i. The Override annotation
ii. The Deprecated annotation
iii. The SuppressWarnings annotation

2. User Defined annotations

Categories:
1. Marker annotations
2. Single-value annotations
3. Full annotations

Meta-Annotation:
Annotations of annotations are meta-annotation. e.g. @Target, @Retention, @Documented.

Exercise: Work with @Deprecated or @Override annotation in Eclipse.

References:

[1] http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html Annotations
[2] http://www-128.ibm.com/developerworks/java/library/j-annotate1/ , Annotations in Tiger, Part 1: Add metadata to Java code, Author: Brett McLaughlin
[3] http://www-128.ibm.com/developerworks/java/library/j-annotate2.html, Annotations in Tiger, Part 2: Custom annotations, Author: Brett McLaughlin
[4] http://www.infoq.com/articles/Annotation-Hammer Annotation Hammer, Author: Venkat Subramaniam
[5] http://www.javaworld.com/javaworld/jw-03-2005/jw-0321-toolbox.html An annotation-based persistence framework, Author:Allen Holub

1 comments:

Anonymous said...

"Annotations are metadata used in source code to be interpreted by the tools and libraries without affecting the execution of the program. Annotations can be interpreted at compile-time or run-time."

Obviously, if they are interpreted at run-time or compilation-time, they DO affect the execution of the program...