Java Annotation Tutorial (Java Annotation Example) - JavaTechWorld

Sunday, 28 May 2017

Java Annotation Tutorial (Java Annotation Example)


Definition- Java Annotation is a type of interface used to provide meta data to java program element such as class, variable, method, interface, enum, package, constructor, and local variables.

Need of annotation- Annotation is given for creating java document comment & xml configuration in java programming so that manual mistake we commiting can be found by compiler those mistake we can solve at development time itself. Therefor project execution is completed successfully.
So annotation is introduced in java 5 as an alternative to document comment & xml configuration files (ex- web.xml).

What are the problem we are facing in project with document comment and xml file configuration -
The maual mistake which we are doing in java document comment and in the xml file configuration are not identified by compiler since they are placing outside of java programe.
These mistakes are identified at execution time by java doclet tool or xml parser or framework.
To identify and solve user mistakes java document and xml configuration files must be developed in java programe using java syntax. So that compiler can validate, identify and inform those manual mistake to programmer then programmer can solve these errors.

What are the manual mistakes ?
  • Developer may add attribute with spellin mistake.
  • Developer may assign wrong type value to attribute.
Syntax to create custom annotation-
Annotation creation is similar as interface creation annotation has "@" symbol before interface keyword.

<modifier> @interface <annotation_name> {

//annotation member
           public static final variables
           non-void, non-parameter method.

@interface Example {

    int a=10;
    String m1();


Annotation Creation Rules-
  1. Annotation member must be
    1. public static final variable
    2. public abstract non-void & non-parameterized method.
  2. The only allowed modifier are public, abstract, strictfp.
  3. It should no be derived from other annotation including "java.lang.annotation.Annotation" explicitly by compiler, 'extends' not allowed for @interface.
  4. The allowed return type are
    1. primitives
    2. String
    3. java.lang.Class
    4. enum
    5. array of the preceding types
  5. Annotation name and return type should not be the same it leads to C.E: Cyclic annotation element type.

© 2014 JavaTechWorld. Designed by Bloggertheme9
Powered by Blogger.