Friday, December 16, 2011

Annotation in Java, the last moment of information


In any football match you will find the coach jumping, screaming telling something to the players. Its not only in football even in Cricket and other sports the coach will try to give some more information to the players on field.Though there was a detail game plan which involve coach, captain and all players much before the match. They know what to do everything is planned, still the coach has to say "one more thing" while the game is in progress.
Same case with us developer, we used to think and  design our codes then write. Still we want to add some more thing while compiling or execution time. I always wish I can say the compiler hey just suppress the warning go ahead compile it, while execution of program we have always want to say something to it about the environment. Well in Java we got some thing called Annotation which serve this purpose.
Annotation can be used to give additional information about a class,method or member to compiler or JVM.
Lets look at some example.
I want to write a class which represent an table in database. We say this kind of of object as Entity object.

@Entity @Table (name = "tbl_employee") 
public class Employee{
   @Id private Long employeeId;
   ...
   private Address address;
   @Clob public Address getAddress() { return address; }
   public void setAddress() { this.address = address; }
}

Here we say Employee is an entity class. It mapped to tbl_employee in database, employeeId is a primary key and getAddress return Clob.
These information is very essential for a ORM framework like JPA or Hibernate.

we use annotation to tune compiler also.

@SuppressWarnings(value = "unchecked")
void myMethod() { }



We use similarly for for run-time  to give more information to JVM. Like everything Java has some inbuilt annotation and user defined also. How to define a custom annotation and where it make sense is another topic. I will write it separately. Mean while you can look for more information here.

2 comments:

Thanks.