(Tutorial) Annotations - metaprogramming facility in J2SE 5.0
Tutorial : Annotations - metaprogramming facility in J2SE 5.0
Annotations are a metaprogramming facility introduced J2SE 5.0. They allow us to mark code with defined tags. Some developers think that the Java compiler understands the tag and work accordingly. This is not right. The tags actually have no meaning to the Java compiler or runtime itself. There are tools that can interpret these tags. For instance: IDEs, testing tools, profiling tools, and code-generation tools understands these tags.
Why use annotations?
Metadata is beneficial for documentation, compiler checking, and code analysis.
One can use metadata to indicate if methods are dependent on other methods, if they are incomplete, if a certain class must reference another class, and so on. You might be thinking that this can also be done using Javadoc since it provides a fairly easy and robust way to document code. Yes, this is correct but the truth is, there are other benefits associated with metadata.
Metadata is used by the compiler to perform some basic compile-time checking. For example there is a override annotation that lets you specify that a method overrides another method from a superclass. At this, the Java compiler will ensure that the behavior you indicate in your metadata actually happens at a code level as well. This might seem trivial to you but the fact is that many developers have spent long nights trying to discover why their code is not working and later realizing that a method has a parameter wrong, which means that the method is not overriding a method from a superclass.
Another great feature of using annotation is code analysis. A good tool like XDoclet can manage all of these dependencies, ensuring that classes that have no code-level connection, but do have a logic-level tie-in, stay in sync. In this case, metadata is really useful.
Annotations and Annotation type
I will differentiate these through an example. You can define a single class and you will always have only one version of the class in the JVM. But you can have 5 or 10 or even more instances of that class in use at any given time. The same is true of annotation types and annotations. An annotation type is same as class, and an annotation is same as instance of that class...
Courtesy:- Java-forums.org
- guru's blog
- Login to post comments
