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 :
- Spring Boot Annotations
- Spring Core Annotations
- Spring Bean Annotations
- Spring Web & REST Annotations
- Spring Scheduling Annotations
- Spring Data Annotations
- Spring Junit Annotations
- Restful Webservice & JAX-RS Annotations
- JAXB Annotations
- JUnit Annotations
- Hibernate & JPA Annotations
- EJB Annotations
Where to use Annotation?
Annotation can be use on following cases:
- Applied as Declaration : Annotation can be use as declaration of classes, fields, methods and other program elements.
- Information for the compiler : Annotations can be used by the compiler to detect errors or suppress warnings.
- Compile-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.
- 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:
- RetentionPolicy.SOURCE : Retained only in the source level and is ignored by the compiler.
- RetentionPolicy.CLASS : Retained by the compiler at compile time, but is ignored by the Java Virtual Machine (JVM).
- 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:
- ElementType.ANNOTATION_TYPE: applied to an annotation type.
- ElementType.CONSTRUCTOR: applied to a constructor.
- ElementType.FIELD : applied to a field or property.
- ElementType.LOCAL_VARIABLE : applied to a local variable.
- ElementType.METHOD : applied to a method-level annotation.
- ElementType.PACKAGE : applied to a package declaration.
- ElementType.PARAMETER: applied to the parameters of a method.
- 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.
- @Retention: @Retention annotation specifies how the marked annotation is stored:
- @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:
- Create custom annotation with @interface.
- Define type of annotation, retention policy and where need to implement that.
- 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:
- EnumConstantNotPresentException
- TypeNotPresentException
- AnnotationFormatError
- AnnotationTypeMismatchException
- IncompleteAnnotationException
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.
You must log in to post a comment.