Java annotations: explored & explained — reprinted

Original address: http://www.javacodegeeks.com/2012/08/java-annotations-explored-explained.html

One of the many wonderful features of Java 5 SE is the introduction of the Annotations construct. Annotations are tags that we can insert into our program source code for some tool to process it and make sense out of it. Annotations processing tools generally use Reflection API (of Java 5 SE) to process the code at source level on Java code or bytecode level to process the class files into which the compiler has placed the annotations. Java Annotations are wonderfully explained in many places around the web,but the only place where I Could find a sensible and complete example was a hard bound book by Prentice Hall Publications named Core Java : Volume II – Advanced Features,authored by Cay S. Horstmann and Gary Cornell.

Almost all the places on web that try to explain Annotations miss the most crucial part of showing us an Annotation Processing Tool (APT) for our custom written annotations and the way to use it from our code. I have used the information from the book to build some Annotations for validating variables and initializing values in them from property files for my project. My observation of the lack of examples over the www for writing custom Java Annotations has motivated me to write this article. So,presenting to you a sample custom Java Annotation to help you write your own Annotations for whatever it is you may be doing.

I will take you through the NullValueValidate annotation whose purpose as its name suggests is to validate the variable it annotates to be containing a non null value. If it finds a null value while processing then it will throw aNullPointerException. Declaring an Annotation

Lets begin by declaring our annotation. This declaration will be used by the code that intends to use the annotation to annotate the variables in its object.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>