Tuesday, April 8, 2014

Java Annotation

Annotation in java is used for the following purposes.
1. Add related information to what it annotates, such as author, created date, version etc.
2. Provide information for the compiler about how to handle certain situations at compiling time, such as suppress certain kind of warnings.
3.  Provide information for software tools to generate code, XML files, and other files at compiling and deployment time.
4. Provide information for program at runtime. For example when you do a class cast, (@Notnull Date)obj.

Annotation is not part of the program, so it should not affect the operation of your code.

Starting in java 8, annotations can be used anywhere a type is used such as type cast, new instance creation, throws and implements clauses. However, annotations can only be used for type, constructor, and method declarations before java 8.

Annotation type is a special type in java. Its declaration is very similar to a declaration of an interface. Its syntax is
      public @<your annotation name> {
            //fields and default values
             Object type() default Object;
             String name();
      }

To create an annotation using the NetBeans IDE. 
1. Right click on a package, choose New and then Other.
2. In the pop up window, select Java under Categories on the left side and select Java Annotation Type under the File Types on the right side. Click the Next button at the bottom.
3. Type the name of your annotation in the Class Name box, and click the Finish button.
4. Make necessary modification to the annotation, such as adding annotations and fields to it.
For example:
      @Documented //To enable the annotation to be included in javadoc
      public @interface Description {
            String author();
            String date();
            String version() default 101;
      }

To use the above annotation on the declaration of a class named BlueSky,

      @Description (author="Sarah Young", date="3/3/2013", version="102")
       public class BlueSky {
             ...............
       }

References:

1. Lesson: Annotations

------------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

No comments:

Post a Comment