Java Annotations: Explored & Explained
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 a NullPointerException
.
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.
package annotation.declaration; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Null Value Validate is, as the name suggests an annotation to * validate whether the parameter is null or not * @author Y.Kamesh Rao * */ @Documented @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface NullValueValidate { String paramName(); }
Note the ‘@’(AT) symbol in front of the ‘interface’ keyword. This is the syntax used to declare an annotation. This is called an annotation interface. The methods of the interface correspond to the elements of the annotation. paramName()
– This is the only element our annotation declaration consists of. It stores the name of the annotated field to display it in a message while processing. Note that the declaration looks like a function declaration. Actually, that is what it is. @interface
actually declares a Java interface whose implementation is provided by the objects that use the annotation. Annotation processors receive the objects that use/implement the annotation and they call annotation interface methods to retrieve the annotation elements. In our case, the NullValueValidateAnnotationProcessor
would receive the object of the class that has some fields annotated using the NullValueValidate
annotation. This processor would then call the paramName()
method to retrieve the value of this annotation element.
We use 3 of the Java provided Annotations to annotate the properties of our declaration. These are alternatively referred to as the Built-In Annotations and are used for ‘Annotating an Annotation’. (Well, there are much tougher tongue twisters than this). @Documented
– Indicates that the annotation declaration has to be included while creating the docs for this project using JavaDocs. By default, Annotations are excluded from the documentation generated using the javadocs
command. @Target
– Indicates the target elements in your java program to which the annotation shall be applied. It can either the Field, Method, Class or the whole Package itself. Our NullValueValidate
annotation shall be applicable to only class fields. Here are the possible values taken by this Enum –
- TYPE – Applied only to Type. A Type can be a Java class or interface or an Enum or even an Annotation.
- FIELD – Applied only to Java Fields (Objects, Instance or Static, declared at class level).
- METHOD – Applied only to methods.
- PARAMETER – Applied only to method parameters in a method definition.
- CONSTRUCTOR – Can be applicable only to a constructor of a class.
- LOCAL_VARIABLE – Can be applicable only to Local variables. (Variables that are declared within a method or a block of code).
- ANNOTATION_TYPE – Applied only to Annotation Types.
- PACKAGE – Applicable only to a Package.
@Retention
– Indicates the retention policy to be used for the annotation. In simple words, for long would we retain the annotation. There are three possible values –
- SOURCE – Annotations are to be discarded by the compiler.
- CLASS – Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time. This is the default behavior.
- RUNTIME – Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.
We have set the RetentionPolicy
to be RUNTIME
since we plan to process the annotations at runtime of the program. @Target
and @Retention
are also called Meta-Annotations.
Annotation Processing Tool
An annotation processor tool, parses the object it receives and takes programmed actions on finding the annotations it is processing in the object under scrutiny. Here is the annotation processor for our previously declared annotation – NullValueValidate
.
package annotation.processor; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import annotation.declaration.NullValueValidate; /** * The class file to actually carry out the validations * for the various validate annotations we have declared * @author Y.Kamesh Rao */ public class NullValueValidateAnnotationProcessor { /** * Method to process all the annotations * @param obj The name of the object where * annotations are to be identified and * processed */ public static void processAnnotations(Object obj) { try { Class cl = obj.getClass(); // Checking all the fields for annotations for(Field f : cl.getDeclaredFields()) { // Since we are Validating fields, there may be many // NullPointer and similar exceptions thrown, // so we need to catch them try { // Processing all the annotations on a single field for(Annotation a : f.getAnnotations()) { // Checking for a NullValueValidate annotation if(a.annotationType() == NullValueValidate.class) { NullValueValidate nullVal = (NullValueValidate) a; System.out.println('Processing the field : '+ nullVal.paramName()); // Setting the field to be accessible from our class // is it is a private member of the class under processing // (which its most likely going to be) // The setAccessible method will not work if you have // Java SecurityManager configured and active. f.setAccessible(true); // Checking the field for a null value and // throwing an exception is a null value encountered. // The get(Object obj) method on Field class returns the // value of the Field for the Object which is under test right now. // In other words, we need to send 'obj' as the object // to this method since we are currently processing the // annotations present on the 'obj' Object. if(f.get(obj) == null) { throw new NullPointerException('The value of the field '+f.toString()+' can't be NULL.'); } else System.out.println('Value of the Object : '+f.get(obj)); } } } catch(Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } } catch(Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } }
Most of the code is self explanatory with comments that it has. Please refer the code for detailed understanding of the same. Basically, it has a static method called processAnnotations
that takes the object of the class which contains annotations that need to be processed. We then use Java Reflection API to process each of the Field in this received object parameter and take necessary actions of null value validation whenever we find a NullValueValidate
Annotation on the field. If a null value is found, we throw the NullPointerException
or we print the value on the console.
Annotation UsagePlease refer the following code that uses the NullValueValidate
annotation that we just implemented. It also uses the NullValueValidateAnnotationProcessor
to process the declared annotations on its field at runtime by calling it from its constructor. Also do note that the annotations are used in a similar fashion as access modifiers like private or public with the variable/field declarations. Usually a newline is entered for better readability of the code. Else, the annotation can very well exist in the same line as the variable/field declaration. The name of the annotation is preceded by an ‘@’(AT) symbol.
package annotation; import annotation.declaration.NullValueValidate; import annotation.processor.NullValueValidateAnnotationProcessor; /** Main class to test the Annotations * @author Y.Kamesh Rao */ public class AnnotationExample { @NullValueValidate(paramName = 'testVar1') private String testVar1; @NullValueValidate(paramName = 'testVar2') private String testVar2; public AnnotationExample() { testVar2 = 'Testing the Null Value Validation...It Works...!'; // Calling the processor to process the annotations applied // on this class object. NullValueValidateAnnotationProcessor.processAnnotations(this); } public static void main(String args[]) { AnnotationExample ae = new AnnotationExample(); } }
Output
Processing the field:testVar1 Value of the Object:Testing the Null Value Validation...It Works...! Processing the field:testVar2 The value of the field private java.lang.String annotation.AnnotationExample.testVar2 cannot be NULL. java.lang.NullPointerException:The value of the field private java.lang.String annotation.AnnotationExample.testVar2 cannot be NULL. at annotation.processor.NullValueValidateAnnotationProcessor.processAnnotation (NullValueValidateAnnotationProcessor.java:66) at annotation.AnnotationExample.(AnnotationExample.java:28) at annotation.AnnotationExample.main(AnnotationExample.java:33)
Conclusion
I had a lot of fun doing this sample annotation program and now I have implemented many custom made Annotations to load properties from property files, validations of database field lengths, etc. Annotations greatly reduces the verbosity of the code thus making it much simpler and readable. Annotations can be used for logging, generating code dependent deployment descriptors and other mechanical and repetitive jobs. I had a lot of fun compiling this article for you guys. I hope you benefit from it.
Reference: Java Annotations: Explored & Explained from our JCG partner Y Kamesh Rao at the OrangeApple blog.
why do we have an incomplete tutorial posted. This is not a ”
sensible and complete example “
where is the rest?
Still today… No complete Tutorial for custom annotations in java..!!!
Hi all, there was a technical glitch that caused the article to be posted incomplete. We have corrected it now to its complete version. Please read along. Sorry for the inconvenience.
Corrected the out put.
Processing the field : testVar1
The value of the field private java.lang.String AnnotationExample.testVar1can’t be NULL.
java.lang.NullPointerException: The value of the field private java.lang.String AnnotationExample.testVar1can’
t be NULL.
at com.jda.annotations.processor.NullValueValidateAnnotationProcessor.processAnnotations(Unknown Sourc
e)
at AnnotationExample.(AnnotationExample.java:23)
at AnnotationExample.main(AnnotationExample.java:27)
Processing the field : testVar2
Value of the Object : Testing the Null Value Validation…It Works…!
I just created an open source project to provide a generic and simple Java Annotation Processor. Using this library you can annotate your annotations for basic validations and avoid writing an Annotation Processor.
Check it out:
https://code.google.com/p/easy-java-annotation-processor
Hi,
This post explains how to create a custom annotation and a corresponding annotation processor.You are programticaly invoking the processor. What I am interested is to see that how is the custom annotation processor triggered automatically at runtime like other JDK or framework annotations.
Exactly. I also want to see how the annotation processor is called automatically.
It is nice article. Neat written code and nice explaination
Hi,
This post explains how to create a custom annotation and a corresponding annotation processor.You are programticaly invoking the processor. What I am interested is to see that how is the custom annotation processor triggered automatically at runtime like other JDK or framework annotations.
Hi,
Very nice article!!
But please can you also reply to the question asked in previous post by Abhilash
“What I am interested is to see that how is the custom annotation processor triggered automatically at runtime like other JDK or framework annotations.”
I am also interested in that. Thanks!!
Thank you . it was good reading
Java Annotations Tutorial and Example
http://javasoftwaretechnology.blogspot.in/2015/11/java-annotations-tutorial-and-example.html
New Features in Java 9
http://javasoftwaretechnology.blogspot.in/2015/12/new-features-in-java-9.html