Tuesday, May 11, 2010

Java Annotations

http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html

Annotations do not directly affect program semantics, but they do affect the way programs are treated by tools and libraries, which can in turn affect the semantics of the running program. Annotations can be read from source files, class files, or reflectively at run time.

Annotations complement javadoc tags. In general, if the markup is intended to affect or produce documentation, it should probably be a javadoc tag; otherwise, it should be an annotation.

Define : An at-sign (@) precedes the interface keyword

/**
* Describes the Request-For-Enhancement(RFE) that led
* to the presence of the annotated API element.
*/
public @interface infoForMethod {
int id();
String s1();
String s2() default "[unassigned]";
String s3(); default "[unimplemented]";
}

Use Annotation:
An annotation is a special kind of modifier, and can be used anywhere that other modifiers (such as public, static, or final) can be used.

@infoForMethod (
id = 123456,
s1= "AAAAA",
s2= "BBBB",
s3= "4/1/2009"
)
public static void aMethod(Date destination) { ... }

---
An annotation type with no elements is termed a marker annotation type
define: public @interface example{ }
Use:
@example
public void aMethod()

--
In annotations with a single element, the element should be named value,
/**
* Associates a copyright notice with the annotated API element.
*/
public @interface Author{
String value();
}

use
m.isAnnotationPresent() 

No comments:

Post a Comment