Java Annotations - Simple Explanation

Java 5.0 added a lot of language features to Java. One of the new features is Annotations. Annotations are tags in the source code that can be processed by a tool, compiler etc. (e.g. JavaDoc comments "@author"). The purpose of annotations is to simplify programming by helping programmers avoid boiler-plate code. Annotations are not part of the program itself, they provide data about the program. They have no effect on the code that they annotate.
Uses for Annotations:
1. Information for the compiler
2. Deployment time processing
3. Runtime processing

How do annotations work?
Annotations can be applied to packages, classes, parameters, variables, fields or methods. It is defined using an "@" syntax. Annotations has a corresponding annotation type. The annotation type defines the content of the metadata.

There are predefined annotations in Java as well as some API's provide their own annotation library. But to define your own annotation, here is how.
Defining a simple Annotation Type:
Annotation type definition is much like an interface definition
Sample code:
Listing A:
/*
* Sample Annotation Type Declaration
*/
1 import java.lang.annotation.ElementType;
2 import java.lang.annotation.Retention;
3 import java.lang.annotation.RetentionPolicy;
4 import java.lang.annotation.Target;
5 @Retention(RetentionPolicy.RUNTIME)
6 @Target(ElementType.METHOD)
7 public @interface Foo{
8 int id();
9 String name () default "George";
10 String description();
11 }

Let us dissect the code above:
Line 5 and Line 6 are meta-annotations. It is an annotation for annotation types.
@Retention(RetentionPolicy.RUNTIME) -- indicates that annotations of this type are to be retained by the VM so they can be read reflective at run time. Please see Java Documentation for annotation retention policies
@Target(ElementType.METHOD) -- indicates that this annotation type can be used to annotate method declarations.


Things to remember when declaring an annotation type:

1. It is similar to declaring normal java interfaces
2. An ("@") at sign precedes the interface keyword
3. Each method declaration defines an element type that must not have any parameters
or a "throws" clause
4. Return types are restricted to primitives, String, Class, enums, annotations and arrays.
5. Methods can have default values.

So once an annotation has been defined you can use it. An annotation with no elements is termed a marker annotation type.

Annotations processing.
So now after you have declared your own annotation type you can write an "Annotations processor" that can read the Java program and take action based on its annotations.
This is a sample code(Listing B) that uses the Foo Annotation.
Listing B:
/*
* Sample Code that uses Foo annotation
*
*/
1 public class Bar{
2 @Foo(id=1, name="Petabyte", description="This is a test")
3 public void method1(){
4 }
5 }

You can run this program(Listing C) and pass in the String "Bar". Foo, Bar should in FooTests classpath during runtime. This will print out the following output.
1
Petabyte
This is a test


Listing C:
/*
* Sample program that will process the Foo Annotation
*/
1 import java.lang.reflect.Method;
2 public class FooTests {
3 public static void main(String[] args) throws Exception {
4 for (Method m : Class.forName(args[0]).getMethods()) {
5 if (m.isAnnotationPresent(Foo.class)) {
6 try{
7 Foo fooAnnotation = m.getAnnotation(Foo.class);
8 if(fooAnnotation != null){
9 System.out.println(fooAnnotation.id());
10 System.out.println(fooAnnotation.name());
11 System.out.println(fooAnnotation.description());
12 }
13 }catch(Exception e){
14 throw e;
15 }
16 }
17 }
18 }
19}

I hope that this gives you a basic understanding of how java annotations works.

Comments

Popular posts from this blog

OAuth 1.0a Request Signing and Verification - HMAC-SHA1 - HMAC-SHA256

Spark DataFrame - Array[ByteBuffer] - IllegalAurmentException

Gensim Doc2Vec on Spark - a quest to get the right Vector