Java Reference
In-Depth Information
Solution
Use the Java Annotations or “Metadata” facility.
Discussion
The continuing success of the open source tool XDoclet —originally used to generate the te-
dious auxiliary classes and deployment descriptor files for the widely criticized EJB2 frame-
work—led to a demand for a similar mechanism in standard Java. Java Annotations were the
result. The annotation mechanism uses an interface-like syntax, in which both declaration
and use of Annotations use the name preceded by an at character ( @ ). This was chosen, ac-
cording to the designers, to be reminiscent of “Javadoc tags, a preexisting ad hoc annotation
facility in the Java programming language.” Javadoc is ad hoc only in the sense that its @ tags
were never fully integrated into the language; most were ignored by the compiler, but @de-
precated was always understood by the compiler (see Dealing with Deprecation Warnings ) .
Annotations can be read at runtime by use of the Reflection API; this is discussed in Using
and Defining Annotations , where I also show you how to define your own annotations. An-
notations can also be read post-compile time by tools such as the RMI and EJB stub generat-
ors (and others to be invented, perhaps by you, gentle reader!).
Annotations are also read by javac at compile time to provide extra information to the com-
piler.
For example, a common coding error is overloading a method when you mean to override it,
by mistakenly using the wrong argument type. Consider overriding the equals method in Ob-
ject . If you mistakenly write:
public
public boolean
boolean equals ( MyClass obj ) {
...
}
then you have created a new overload that will likely never be called, and the default version
in Object will be called. To prevent this, an annotation included in java.lang is the Over-
ride annotation. This has no parameters but simply is placed before the method call. For ex-
ample:
/**
* AnnotationOverrideDemo - Simple demonstation of Metadata being used to
Search WWH ::




Custom Search