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.
WHAT IS ANNOTATION ?
               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).
PREDEFINED ANNOTATIONS
                Lets have a look at the predefined Annotations in java.lang package.
An annotation always begins with @ symbol
                 @Deprecated
                 @Override
                 @SuppressWarnings

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
                 @Target
                 @Retention
                 @Documented
                 @Inherited


USES OF ANNOTATION
            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{
                   @Deprecated
                    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.
                   @Override
                   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.
                   @SuppressWarnings(”deprecation”)
                   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() { …. }

ANNOTATION TYPES
                 There are three annotation types:
                    Marker
                    Single-Element
                    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 :
                   @MyAnnotation
                    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.
 Example:
                   public @interface MyAnnotation {
                   String doSomething();
                   }

     Usage:
                  @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();
                   }

 Usage:
                  @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:
                              primitives
                              String
                              Class
                              enum
                              array of the above types

META ANNOTATION EXPLAINED
@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 :
                          @Target(ElementType.METHOD)
                           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 :

                       @Retention(RetentionPolicy.RUNTIME)
                        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 :
              @Documented
               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.

References
http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/java/javaOO/annotations.html
http://download.oracle.com/docs/cd/E17476_01/javase/1.5.0/docs/guide/language/annotations.html
http://www.developer.com/java/other/article.php/3556176/An-Introduction-to-Java-Annotations.htm

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

Comments

Popular posts from this blog

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

செந்தாழம் பூவில் வந்தாடும் தென்றல் (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.

Rasaali Song Lyrics and Translation - To my best (Achcham Enbadhu Madamaiyada)

          I have tried my best to translate this awesome composition of A.R.Rahman - Rasaali for the movie அச்சம் என்பது மடமையடா (Acham Enbadhu Madamaiyada) which lazy people tend to call it AEM. Tamil is such a beautiful language, its difficult to get the exact ecstasy until you know the language. Divinity at its best.  Movie is not yet released, but I guess the situation is lead actor and actress is going on a bike ride when they sing this song to express their feelings. Credits to lyricist Thamarai. Song :   Rasaali Lyrics : Thamarai Music : A.R.Rahman Singers : Sathya Prakash, Shashaa Tirupati Male: Parakkum rasaaliye rasaaliye nillu.. Ingu nee vegama naan vegama sollu.. Gadigaaram poi sollum endre naan kanden.. Kizhakellam merkaagida.. kandene.. பறக்கும் இராசாலியே இராசாலியே நில்லு.. இங்கு நீ வேகமா நான் வேகமா சொல்லு.. கடிகாரம் பொய் சொல்லும் என்றே நான் கண்டேன்.. கிழக்கெல்லாம் மேற்காகிட.. கண்டேனே.. Flying falcon, please wait..  (Comparing his girl to a