Skip to main content

Java Annotations

Hi Folks,
               This is technical one. You may think for a while “What the *$#*# is this? Arvind writing technical post?!?!? ” No wonder, I am writing it. And this post I dedicate to my trainer Arun who provided us this wonderful notes regarding Annotations. Its about Java Annotations. Come on, Lets dig deep into it.
               Annotations are like meta-tags that you can add to your code and apply them to package declarations, type declarations, constructors, methods, fields, parameters, and variables. Annotations do not directly affect program semantics, but they do affect the way programs are treated by tools and libraries, which can in turn affect the semantics of the running program.
THE BASICS               There are two things you need to consider with annotations.
                       One is the “annotation” itself.
                       Another is the “annotation type“.

              An “annotation” is the meta-tag that you will use in your code to give it some life. An “annotation type” is used for defining an annotation. You will use it when you want to create your own custom annotation(User defined). First we shall see how to use the “annotation” and then we shall see how to use “annotation type” (writing user defined annotation).
                Lets have a look at the predefined Annotations in java.lang package.
An annotation always begins with @ symbol

In java.lang.annotation package, these annotations are called as “Meta – Annotations”.
 Meta – Annotations : Meta-annotations, which are actually known as the annotations of annotations, contain four types

            Annotations have a number of uses, among them:
                 Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.
                 Compiler-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and  so forth.
                 Runtime processing — Some annotations are available to be examined at runtime.
How the Java compiler tool uses it?
Example 1:               Let’s start with the predefined annotation @Deprecated defined in java.lang package.
                   Class DeprecatedDemo{
                    static void deprecatedMethod() { }
                    Class  TestDeprecatedAnnotation{
                    public static void main(String args[]) {
                    DeprecatedDemo. deprecatedMethod();

                Whenever you invoke the deprecatedMethod() from any program then the compiler “generates a warning “ when the program is compiled.
Example 2 :               @Override – the @Override annotation informs the compiler that the element is meant to override an element declared in a superclass, it helps to prevent errors.
                   int overriddenMethod() {
                    ……………………………….. // some code
                   return 100;

                If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.
Example 3:             @SuppressWarnings—the @SuppressWarnings annotation tells the compiler to suppress specific warnings that it would otherwise generate. In the example below, a deprecated method is used and the compiler would normally generate a warning. In this case, however, the annotation causes the warning to be suppressed.
                   void useDeprecatedMethod() {
                   DeprecatedDemo. deprecatedMethod();    //deprecation  warning - suppressed

ANNOTATION TYPES -BASICS                                           
               An annotation defitype nition takes an “at” (@) sign, followed by the interface keyword plus the annotation name. Additionally, you can put data within parenthesis after the annotation name.
 Example to Define an Annotation (Annotation type)                   public @interface MyAnnotation {
                   String doSomething();

 Example to Annotate Your Code (Annotation)
                   @MyAnnotation (doSomething=”What to do”)
                   public void mymethod() { …. }

                 There are three annotation types:
                    Full-value or multi-value

Marker Annotation Type
            Marker: Marker type annotations have no elements, except the annotation name itself.
 Example :
                   public @interface MyAnnotation
                   { }

 Usage :
                    public void myMethod()
                    { …. }

Single-Element Annotation type
          Single-element, or single-value type, annotations provide a single piece of data only. This can be represented with a data=value pair or, simply with the value (a shortcut syntax) only, within parenthesis.
                   public @interface MyAnnotation {
                   String doSomething();

                  @MyAnnotation (”What to do”)
                   public void mymethod() { …. }

Multi-value Annotation type
          Full-value type annotations have multiple data members. Therefore, you must use a full data=value parameter syntax for each member.
 Example:                   public @interface MyAnnotation {
                   String doSomething();
                   int count;
                   String date();

                  @MyAnnotation (doSomething=”What to do”, count=1, date=”09-09-2005″)
                   public void mymethod() { …. }

Rules of Thumb for Defining Annotation Type
     Here are some rules-of-thumb when defining an annotation type:
                    Annotation declaration should start with an ‘at’ sign like @, following with an interface keyword, following with the annotation name.
                    Method declarations should not have any parameters.
                    Method declarations should not have any throws clauses.
                    Return types of the method should be one of the following:
                              array of the above types

@Target  - The target annotation indicates the targeted elements of a class in which the annotation type will be applicable.
                           @Target(ElementType.TYPE)—can be applied to any element of a class
                           @Target(ElementType.FIELD)—can be applied to a field or property
                           @Target(ElementType.METHOD)—can be applied to a method level annotation
                           @Target(ElementType.PARAMETER)—can be applied to the parameters of a method
                           @Target(ElementType.CONSTRUCTOR)—can be applied to constructors
                           @Target(ElementType.LOCAL_VARIABLE)—can be applied to local variables
                           @Target(ElementType.ANNOTATION_TYPE)—indicates that the declared type itself is an annotation type
             Where ElementType is an enum in java.lang.annotation package. The constants of this enumerated type provide a simple classification of the declared elements in a Java program.
Example :
                           public @interface Test_Target {
                           public String doTestTarget();

            Next, create a class that will use the @Test_Target annotation.
                           public class TestAnnotations {
                           public static void main(String arg[]) {
                           new TestAnnotations().doTestTarget();

                           @Test_Target(doTestTarget=”Hello World !”)
                           public void doTestTarget() {
                           System.out.printf(”Testing Target annotation”);

            The @Target(ElementType.METHOD) indicates that this annotation type can be used to annotate only at the method levels. If you compile the preceding code, no warning messages will be shown.
@Retention  - The retention annotation indicates where and how long annotations with this type are to be retained.
           There are three values:
                         RetentionPolicy.SOURCE—Annotations with this type will be retained only at the source level and will be ignored by the compiler.    
                         RetentionPolicy.CLASS—Annotations with this type will be by retained by the compiler at compile time, but will be ignored by the VM .     
                         RetentionPolicy.RUNTIME—Annotations with this type will be retained by the VM so they can be read only at run-time .

 Example :

                        public @interface Test_Retention {
                        String doTestRetention();

          In this example, the @Retention(RetentionPolicy.RUNTIME) annotation indicates that your @Test_Retention annotation will be retained by the VM so that it can be read reflectively at run-time.
 Note  -  The concept of using annotations at runtime using reflection is explained in the later part of this post.
 @Documented - The documented annotation indicates that an annotation with this type should be documented by the javadoc tool. By default, annotations are not included in javadoc. But if @Documented is used, it then will be processed by javadoc-like tools and the annotation type information will also be included in the generated document.
 Example :
               public @interface {
               String doTestDocument();

               public class TestAnnotations {
               public static void main(String arg[]) {
               new TestAnnotations().doSomeTestRetention();
               new TestAnnotations().doSomeTestDocumented();
               @Test_Retention (doTestRetention=”Hello retention test”)
                public void doSomeTestRetention() {
                System.out.printf(”Testing annotation ‘Retention’”);
                @Test_Documented(doTestDocument=”Hello document”)
                public void doSomeTestDocumented() {
                System.out.printf(”Testing annotation ‘Documented’”);

          Note: javadoc is a tool used for generating html docs for Java classes.
@Inherited –  Indicates that an annotation type is automatically inherited
            This meta-annotation type has no effect if the annotated type is used to annotate anything other than a class. Note also that this meta-annotation only causes annotations to be inherited from superclasses; annotations on implemented interfaces have no effect. By default annotations are not inherited.
    Example :
                          @MyAnnotation class Super {
                           public void foo() {}
                           class Sub extends Super {
                           public void foo() {}

             If an annotation type has the meta-annotation @Inherited then an annotation of that type on a class will cause the annotation to be inherited by sub-classes.
So, in the example above, if the MyAnnotation type had the @Inherited attribute, then Sub would have the MyAnnotation annotation.


            Thank you for reading this post and hope you all got a overview of what annotation is. Meet you all in my next post.


Popular posts from this blog

செந்தாழம் பூவில் வந்தாடும் தென்றல் (Senthazham poovil vandhaadum thendral) song lyrics and meaning

I am so astonished by the creativity of Kaviyarasu Kannadasan and the language itself. This is one of my favourite song in the tamil movie called Mullum Malarum. Wonderful movie with extraordinary music composition by famous Isaigyaani Ilayaraja sir. 
                I will try giving the exact meaning of this song which portrays how beautiful women are and you can relate to anything which comes to your mind when you read it along. Kannadasan, Ilayaraja and K.J.Yesudas, a combination that shouldn't be missed.

Song:   Senthaazham poovil vandhaadum thendral Lyrics: Kannadasan Music: Ilayaraja Singer: K.J.Jesudas
செந்தாழம் பூவில் வந்தாடும் தென்றல்  என் மீது மொதுதமா.. (x2) பூ வாசம் மேடை போடுதம்மா  பெண் போல ஜாடை பேசுதம்மா.. அம்மம்மா ஆனந்தம்.. அம்மம்மா ஆனந்தம்..
Senthaazham poovil vandhaadum thendral  En meedhu modhudhamaa.. Poo vaasam medai podudhamaa Penn pola jaadai pesudhamma.. Ammammaa aanandham.. ammammaa aanandham..
The breeze that dances over screw pine flower  comes…

English Translation of "Voda Voda " song from Mayakam Enna

Hi guys
       Too many Tamil post and my Non-Tamil readers would have really bugged up with my previous posts. Many non-tamil people who hear this song "Voda Voda Voda" from Mayakam Enna is wondering what is the exact meaning of this song. They don't know the meaning but still they enjoy it. Now read this post, know the meaning and sing it along.

       I have differentiated the original lyrics of the song in blue color and the meaning of it in the next line in red color. Here we go...

Voda voda voda thooram korayala... Running running running distance didn't get reduced... Paada paada  paada paatum mudiyala... Singing singing singing song didn't get over... Poga poga poga onum puriyala, aaga motham onum velangala... Time passing by nothing able to grasp, totally nothing understood...
Free ah suthum podhu figure illaye...
While roaming freely figure was not there... Pudicha figurum ipa free ah illaye... The figure I liked is not free now.. Kayil bat iruku ball illaye, life…

திருக்குறள் - கல்யாண பால்

நீண்ட நாட்கள் ஆகியும் பதிவை புதிப்பிக்க முடியாததற்கு வருந்துகிறேன். முந்தைய பதிவின் தொடர்ச்சியாக கல்யாண பால். இதற்கு முன் சைட் பால் மற்றும் காதல் பால் படித்திருப்பீர்கள் என நம்புகிறேன். படிகாதோற்கு இதோ இணைப்பு - மற்றும் . நான் எழுதும் இக்குறள் சிரிப்பதற்காகவும் மற்றும் சிந்திபதற்காக மட்டுமே.. யார் மனதையும் புண்படுத்தும் நோக்கம் இல்லை.

கல்யாண பால்
காதலில் ஜெயமென்றால் கணவன் அஃதில்லையேல் 
அடுத்தப்பெண்ணை  தேடல் ஜெயம்.

மனைவி அமைவது இறைவன் கொடுத்தவரம்
அதைமாற்றி அமைப்பவன் புத்திசாலி.

பெண்ணுக்கு கழுத்தில் ஏறும் தாளிசங்கிலி
அஃது ஆணின் மரணசங்கிலி.

ஆண் பெண் திருமணம் செய்துவிடல்
சந்தோஷம் என்பது கணவாம்.

தாரம் தாய்போற் இருப்பின் அதிர்ஷ்டம்
நாய்போற் இருப்பின் துரதிருஷடம்.

 கல்யாணம் ஆனபின் குழந்தைப்பேறு அழகு
முன்னேரே பெற்றால் அசிங்கம்.

கல்யாணம் சுவர்கத்தில் நிச்சயிக்கப்படும் ஆனபின்
வாழ்வோர் நரகத்திலே வாழ்வார்.  

தாய் தாரம் அடிதடிக்கு நடுவில்
ஆட்டநடுவராக இருத்தல் ஆபத்து.�����…