Java Annotations

Java Annotations

Java annotations are the facility to add meta-data facility to the java elements. An annotation is a special form of syntactic metadata and it is helps to add to java source code classes, methods, variables, parameters and packages may be annotated. An annotation gives data about a program. It is not part of the program itself and no direct effect on the operation of the code.

Eg: –

<div id="_mcePaste">public class Animal {</div>
<div id="_mcePaste">public void speak() {</div>
<div id="_mcePaste">public String getType() {</div>
<div id="_mcePaste">return “Generic animal”;</div>
<div id="_mcePaste">}</div>
<div id="_mcePaste">}</div>
<div id="_mcePaste">public class Cat extends Animal {</div>
<div id="_mcePaste">@Override</div>
<div id="_mcePaste">public void speak() { // This is a good override.</div>
<div id="_mcePaste">System.out.println(“Meow.”);</div>
<div id="_mcePaste">}</div>
<div id="_mcePaste">@Override</div>
<div id="_mcePaste">public String gettype() { // throws compile warning due to mistyped name.</div>
<div id="_mcePaste">return “Cat”;</div>
<div id="_mcePaste">}</div>
<div id="_mcePaste">}</div>
<div id="_mcePaste">}</div>

Uses of annotation

1)      Information for the compiler: – Annotations helps the compiler to detect errors or suppress warnings.

2)      Compiler-time and deployment-time processing: – Software tools can process annotation information to generate code, XML files, and so forth.

3)      Runtime processing: – Annotations uses the runtime process.

Rules for defining Java annotations

  1. Annotation declaration should start with an ‘at’ sign like @, following with an interface keyword, following with the annotation name.
  2. Method declarations should not have any parameters.
  3. Method declarations should not have any throws clauses.
  4. Return types of the method should be one of the following:-
    1. primitives
    2. String
    3. Class
    4. enum
    5. array of the above types

The below annotations are used for annotations applied to other annotations:-

@Retention: – Specifies how the marked annotation is stored — Whether in code only, compiled into the class, or available at runtime through reflection.

@Documented: – Marks another annotation for inclusion in the documentation.

@Target: – Marks another annotation to restrict what kind of java elements the annotation may be applied to

@Inherited: – Marks another annotation to be inherited to subclasses of annotated class (by default annotations are not inherited to subclasses).

1)      Built in annotations: – Java specifies the set of annotations which are built into the language. They are,

  1. @Override: -Checks that the function is an override. Causes a compile warning if the function is not found in one of the parent classes.

Eg: –

@Retention(RetentionPolicy.CLASS)
@Target(ElementType.RUNTIME)
public @interface Override
{
}
public class Employee
{
protected void startWork()
{
// Code that will start to do some work.
}
protected void endWork()
{
// Code to end the work.
}
}
public class Manager extends Employee
{
@Override
protected void startWork()
{
// Code that will start to do some work.
}
@Override
protected void endWork()
{
// Code to end the work.
}
}
  1. @Deprecated: – Marks the function as absolute. Causes a compile warning if the f unction is used. When we want to inform the compiler that a method is deprecated we can use this. So, when a method is annotated with @Deprecated and that method is found used in some place, then the compiler generates a warning.

Eg: –

package j2eebrain.deprecated;
public class MyOldClass
{
/**
* This method has become obsolete. Client Applications now can
* depend on
* {@link #myAlternativeMethod()}    to achieve the same affect.
*/
@Deprecated
public void myDeprecatedMethod()
{
// Obsolete code here.
}

public void myAlternativeMethod()
{
// Revised code here.
}
}

The class MyOldClass has a method myDeprecatedMethod() which is tagged as Deprecated.

  1. @SuppressWarnings: – Instructs the compiler to suppress the compile time warnings specified in the annotation parameters. This is like saying, “I know what I am doing, so please shut up!” We want the compiler not to raise any warnings and then we use this annotation.

Eg:

@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings
{
String[] value();
}

@SuppressWarnings(“unchecked”)
public static List toList(Object[] array)
{
return Arrays.asList(array);
}

2)      User defined annotation: –  In java user defined annotations are also possible.

Eg: –

@Target({ElementType.FIELD, ElementType.LOCAL_VARIABLE})
public @interface Persistable
{
String fileName();
}

We have defined the target for this annotation as field and local variable meaning that this Annotation can be applicable only to Java Fields and Local variables. The type (String, in this case) followed by the property name which looks like a method definition fashion. The below syntax define how to apply the user defined annotations on java elements.

Eg: –

@Persistable(fileName = “movies.txt”) Movie movie;

The example tells to save all the information about the Movie object to the file called movies.txt. Normally annotations are interpreted by tools and once tools read these annotation informations, they will perform the required operation.

3)      Types of annotations: – Java handling different types of annotations. They are,

1)      Documented: – If an annotation type is annotated with @Documented then wherever this annotation is used those elements should be documented using Javadoc tool.

2)      Inherited: – This meta annotation denotes that the annotation type can be inherited from super class. When a class is annotated with annotation of type that is annotated with Inherited, then its super class will be queried till a matching annotation is found.

3)      Retention: – This meta-annotation denotes the level till which this annotation will be carried. When an annotation type is annotated with meta annotation Retention, RetentionPolicy has three possible values:

Eg: –

@Retention(RetentionPolicy.RUNTIME)
public @interface Developer {
String value();
}

Class: – The annotation value as class it will be compiled and included in the class file.

Runtime: – The retention value is ‘Runtime’ the annotation will be available in JVM at runtime. We can write custom code using reflection package and parse the annotation.

Source: – This annotation will be removed at compile time and will not be available at compiled class.

4)      Target: – This meta annotation says that this annotation type is applicable for only the element (ElementType) listed. Possible values for ElementType are, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE.

Syntax: –

@Target(ElementType.FIELD)
public @interface FieldInfo { }