Java : Annotation Tutorial


What is Annotation?

Annotations, a form of metadata, provide data about a program that is not part of the program itself and  no direct effect on the operation of the code they annotate.

See Also :

Where to use Annotation?

Annotation can be use on following cases:

  1. Applied as Declaration : Annotation can be use as declaration of classes, fields, methods and other program elements.
  2. Information for the compiler : Annotations can be used by the compiler to detect errors or suppress warnings.
  3. Compile-time and deployment-time processing : Software tools can process annotation information to generate code, XML files, and so forth.
  4. Runtime processing : Some annotations are available to be examined at runtime.
  5. Applied as Type : After Java 8+, annotation can we use as type also.

Points to remember

  • The at sign character (@) indicates to the compiler that what follows is an annotation.
  • If the annotation has no elements, then the parentheses can be omitted.
  • The annotation type can be one of the types that are defined in the java.lang or java.lang.annotation packages.
  • When annotation used as declaration, as convention each annotation often appears on its own line.

Format of Annotations

Below are some types of annotation and uses:

Pre-Defined Annotation without values

@Entity
public class Employee
{
}

@Override
public String toString()
{
return "FacingIssuesOnIT";
}

Annotations with multiple values

@Author(
name = "Saurabh Gupta",
date = "06/04/2017"
)
class MyTestClass() { ... }

Annotations with single value

@SuppressWarnings(value = "unchecked")
void myTestMethod() { ... }

or

//if there is only one value avoid use fields to make more clean code
@SuppressWarnings("unchecked")
void myTestMethod() { ... }

Use of Multiple annotation

@Author(name = "Saurabh Gupta")
@EBook
class MyTestClass { ... }

Repeatating Annotation (Java 8+)

If the annotations have the same type, then this is called a repeating annotation:

@Author(name = "Saurabh Gupta")
@Author(name = "Navin kumar")
class MyTestClass { ... }

Annotation as Type (Java 8+)

After Java 8 expended scope of using Annotation as below:

Class instance creation expression:

new @Interned MyTestClass();

Type cast:

myString = (@NonNull String) str;

Implements clause:

class UnmodifiableList implements
@Readonly List { ... }

Thrown exception declaration

void monitorSpeed() throws
@Critical SpeedException { ... }
This form of annotation is called a type annotation.

Now you have learn about Annotations , use of annotations  and enhancement in scope of annotations after java 8+. Now we will talk about predefined annotations and creation of custom annotation.

Predefined Annotation

  • @Deprecated : @Deprecated annotation indicates that the marked element is deprecated and should no longer be used. The compiler generates a warning whenever a program uses a method, class, or field with the @Deprecated annotation. When an element is deprecated, it should also be documented using the Javadoc @deprecated tag,
  • @override : @Override annotation informs the compiler that the element is meant to override an element declared in a superclass. use from Inheritance and interface.
  • @SuppressWarnings : @SuppressWarnings annotation tells the compiler to suppress specific warnings that it would otherwise generate.
    // use a deprecated method and tell
    // compiler not to generate a warning
    @SuppressWarnings("deprecation")
    void useDeprecatedMethod() {
    // deprecation warning - suppressed
    objectOne.deprecatedMethod();
    }
    @SuppressWarnings({"unchecked", "deprecation"})
    
  • @SafeVarargs: @SafeVarargs annotation, when applied to a method or constructor, asserts that the code does not perform potentially unsafe operations on its varargs parameter. When this annotation type is used, unchecked warnings relating to varargs usage are suppressed.
  • @FunctionalInterface: @FunctionalInterface annotation, introduced in Java SE 8, indicates that the type declaration is intended to be a functional interface, as defined by the Java Language Specification.

Annotations that apply on other annotations (Meta annotation). These annotations defined in java.lang.annotation.

    • @Retention:  @Retention annotation specifies how the marked annotation is stored:
      1. RetentionPolicy.SOURCE : Retained only in the source level and is ignored by the compiler.
      2. RetentionPolicy.CLASS : Retained by the compiler at compile time, but is ignored by the Java Virtual Machine (JVM).
      3. RetentionPolicy.RUNTIME : Retained by the JVM so it can be used by the runtime environment.
    • @Documented: Indicates that whenever the specified annotation is used those elements should be documented using the Javadoc tool. (By default, annotations are not included in Javadoc.).
    • @Target: Marks another annotation to restrict what kind of Java elements that annotation can be applied to. A target annotation specifies one of the following element types as its value:
      1. ElementType.ANNOTATION_TYPE: applied to an annotation type.
      2. ElementType.CONSTRUCTOR: applied to a constructor.
      3. ElementType.FIELD : applied to a field or property.
      4. ElementType.LOCAL_VARIABLE : applied to a local variable.
      5. ElementType.METHOD : applied to a method-level annotation.
      6. ElementType.PACKAGE : applied to a package declaration.
      7. ElementType.PARAMETER: applied to the parameters of a method.
      8. ElementType.TYPE: applied to any element of a class.
    • @Inherited : This annotation applies only to class declarations. @Inherited annotation indicates that the annotation type can be inherited from the super class. (This is not true by default.) When the user queries the annotation type and the class has no annotation for this type, the class’ superclass is queried for the annotation type.
  • @Repeatable: @Repeatable annotation, introduced in Java SE 8, indicates that the marked annotation can be applied more than once to the same declaration or type use.

Custom Annotation

We can define our own annotation i.e called as custom annotation. We have to follow below steps while creation of custom annotation:

  1. Create custom annotation with @interface.
  2. Define type of annotation, retention policy and where need to implement that.
  3. define values of annotation. if required set some default values by using keyword as default.

Here is custom annotation for document the class changes

 package com.common.annotations;

import java.lang.annotation.Documented;

@Documented
public @interface ChangeRecord {
	   String author();
	   String date();
	   int currentRevision() default 1;
	   String lastModified() default "N/A";
	   String lastModifiedBy() default "N/A";
	   // Note use of array
	   String[] reviewers();
}

Use of custom annotation over documentation of class changes.

/** Copyright FacingIssuesOnIT.com . To Present All rights reserved
*/
package com.common.annotations;

import java.lang.annotation.Annotation;

@ChangeRecord
(
	author = "Saurabh Gupta",
	date = "3/4/2019",
	currentRevision = 2,
	lastModified = "5/4/2019",
	lastModifiedBy = "Gaurav Gupta",
	reviewers = {"Rajkumar", "Raghav", "Rajesh"}
)
public class CustomAnnotationExample {

	public static void main(String[] args) {

	}
}

Repeatable Annotation Example

Java 8+ introduced repeatable annotation so that same annotation can be use multiple time. For example create custom annotation to implement as repeatable annotation.

Create Custom Repeatable Annotation

/** Copyright FacingIssuesOnIT.com . To Present All rights reserved
*/
package com.common.annotations;
import java.lang.annotation.Repeatable;
/**
* Repeatable annotation introduced in <strong>java 8+</strong> to use repeatative task */

@Repeatable(Schedules.class)
public @interface Schedule {
String dayOfMonth() default "first";
String dayOfWeek() default "Mon";
int hour() default 2;
}

Create of array of repeatable annotation

/** Copyright FacingIssuesOnIT.com . To Present All rights reserved
*/
package com.common.annotations;
public @interface Schedules {
Schedule[] value();
}

Use of repeatable annotation

/** Copyright FacingIssuesOnIT.com . To Present All rights reserved */
package com.common.annotations;
import java.util.Date;
public class RepeatableAnnotationExample {
    public static void main(String[] args) {
	// TODO Auto-generated method stub
	} 

@Schedule(dayOfMonth="last")
@Schedule(dayOfWeek="Fri", hour=23)
   public void doPeriodicCleanup() {
     System.out.println("Clean up started at :"+new Date());
   }
}

Annotation Exceptions

Below are some annotation related exceptions which occurred at runtime:

Reflection for Annotation

In Java 8+ introduced some new reflection apis to retrieve annotation related information from different elements type like classes, interfaces, method, type etc.

Follow below link to get all  reflections apis for annotation:

Java : Reflection for Annotations

Conclusion

Here you have learned about annotation in depth knowledge:

  • Annotation and pre-defined annotation and uses.
  • Scope of annotations in Java 8+.
  • Implementation of annotation.
  • Custom Annotation with exmaple
  • Repeatable  Annotation with example.
  • Reflection for Annotations (Java 8+) APIs.
  • Exception occurred by annotations.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s