A Complete Introduction to Annotations in Java

Last updated on Jul 21,2020 2.4K Views
Tech Enthusiast working as a Research Analyst at Edureka. Curious about learning... Tech Enthusiast working as a Research Analyst at Edureka. Curious about learning more about Data Science and Big-Data Hadoop.

A Complete Introduction to Annotations in Java

edureka.co

Annotations in Java are the special kind of Java constructs used as decorative syntactic metadata for the class elements used in the source code to provide special information to guide the java interpreter during code translation. In this article, we will discuss the following concepts.

 

What are Annotations in Java?

Annotations are used to represent the syntactic metadata related to the class, interface, methods or fields used in the source code and some additional information which is used by java interpreter and the JVM. In this article, we will discuss the following concepts.

 

Why do we need Annotations?

Compiler instructions

The built-in annotations such as @Override, @Deprecated, and @SuppressWarnings provide the interpreter, about the information related to the execution of code. For instance, @Override is used to instruct the interpreter that the annotated method is being overridden. 

Build-time instructions

Annotations provide build-time/compile-time instructions to the interpreter that are used by software build tools for generating code, Pom.XML files etc.

Run-time instructions

Annotations can be defined at the run-time so that they could be made available to access in the run-time and provide instructions to the program.

Now, let us discuss their types.

 

Types of Annotations 

Annotations are typically divided into three types as described below:

 

Marker Annotations

Marker Annotations are declared for the purpose of a Mark which describes their presence. They do not include any members in them which makes them stay empty. @Override is an example for Marker Annotations.

package Types;
@interface MarkerTypeAnnotation{}

Single Annotations

The name itself specifies that the Single Annotations are designed to include a single member in them. The shorthand method is used to specify the value to member declared inside the Single Annotation.

package Types;
@interface SingleTypeAnnotation{
int member() default 0;
}

Full Annotations

Full or Multiple Annotations are similar to Single Annotations but they can include multiple members/ name, value, pairs.

package Types;
@interface FullAnnotationType{  
     int member1() default 1;  
     String member2() default "";  
     String member3() default "abc";  
}

Java also offers some built-in Annotations.

 

Built-in Annotations in Java

Retention Annotations

Retention Annotations are designed to indicate for how long a particular annotation with the annotated type is to be retained. The following is an example of Retention Annotation

package Retention;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface EdurekaAnnotation {
     String MethodName();
     String Description();
}

class RetentnionTest{
      @EdurekaAnnotation(MethodName = "Retention Annotation test", Description = "testing annotations")
       public void TestMethod(){
       }
}

Deprecated Annotations

Deprecated annotation is used for informing the compiler that the particular method, class or field is unimportant and it indicates that a declaration is outdated.

package Deprecated;

public class Deprecated {
     @Deprecated
      public void Display() {
            System.out.println("Deprecated Annotation test Method()");
      }

      public static void main(String args[]) {
            Deprecated Dep = new Deprecated();
            Dep.Display();
      }
}

Override Annotations

It is a Marker type Annotation. An Override Annotation is designed to ensure that a super-class method is overridden, and not overloaded.  A method annotated with @Override is expected to override a method from a super-class else a compile-time error will be thrown.

package Override;

class Parent {
      public void Display() {
             System.out.println("Parent Class Method exrecuting()");
      }
      public static void main(String args[]) {
      Parent P1 = new Child();
      P1.Display();
      }
}
class Child extends Parent {
     @Override
      public void Display() {
            System.out.println("Child Class Method exrecuting()");
      }
}

Suppress Warning Annotations

Suppress Warning Annotations are used to eliminate/suppress interpreter warnings during the program execution. Suppress Warning annotation can be applied to any type of declaration. The following is an example of this type of annotations.

package SuppressWarning;

class DeprecatedTest {
    @Deprecated
     public void Display() {
          System.out.println("Deprecated test display()");
     }
}

public class SuppressWarning{
     @SuppressWarnings({"checked", "deprecation"})
       public static void main(String args[]) {
       DeprecatedTest d1 = new DeprecatedTest();
       d1.Display();
       }
}

Inherited Annotations

Annotations in Java are not inherited to subclasses by default. Hence, the Inherited Annotation marks the annotation to be inherited to subclasses. The following is an example of Inherited Annotation

package Inherited;
       public @interface MyAnnotation {
}
package Inherited;
       public @interface MyInheritedAnnotation {
}
package Inherited;
@MyAnnotation
@MyInheritedAnnotation
public class BaseClass {
}
package Inherited;
public class SubClass extends BaseClass {
}
package Inherited;
public class ExampleMain {
      public static void main(String[] args) {
            MyAnnotation myannotation = SubClass.class.getAnnotation(MyAnnotation.class);
            System.out.println(myannotation);
            MyInheritedAnnotation myannotation2 = SubClass.class.getAnnotation(MyInheritedAnnotation.class);
            System.out.println(myannotation2);
     }
}

Target Annotations

Target Tags are used to specify the type of Annotation used. The Annotation Library declares many constants to specify the type of element where the annotation is needed to be applied, such as TYPE, METHOD, FIELD etc. We can access the Target tags from java.lang.annotation.ElementType

 

Element TypeLocation of the Annotations to be applied
TYPEClass, Interface or Enumeration
FIELDFields
METHODMethods
CONSTRUCTORConstructors
LOCAL_VARIABLELocal variables
ANNOTATION_TYPEAnnotation Type
PARAMETERParameter

 

package Target;
public @interface CustomAnnotation {
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target({ElementType.METHOD})
public @interface MyCustomAnnotation {
}
public class target {
      @CustomAnnotation
       public void myMethod(){
             System.out.println("Hello World");
       }
}

Documented Annotations

It is a marker type Annotation which is used to communicate with a tool that documents the annotation. By default, annotations are not included by Javadoc comments. The use of Documented annotation in the code enables Javadoc to process and include the annotation-type information in the resultant document.

package Documented;
import java.lang.annotation.Documented;
@Documented
public @interface DocumentAnnotation {
      class AddNumbers{
             public static void main(String args[]){
                   int x=10,y=20,z;
                   z = x + y;
                  System.out.println("Sum of the integers = " + z);
             }
       }
}

Custom Annotations in Java

Java Custom annotations are the User-defined annotations that are easy to create and use. The @Interface element is used to declare an annotation. An example of a custom annotation is as follows.

package Custom;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@ interface TestAnnotation {
       String Developer() default "Edureka";
       String Expirydate();
}

public class Custom {
        @TestAnnotation(Developer="Rajesh", Expirydate="01-Aug-2026")
         void function1() {
                 System.out.println("Testing Annotation method 1");
          }

         @TestAnnotation(Developer="Anil", Expirydate="01-Oct-2025")
          void function2() {
                System.out.println("Test Annotation method 2");
          }
          public static void main(String args[]) {
                  System.out.println("Customized Annotations Example");
          }
}

With this, we have come to the end of this article. I hope you have understood the basics of annotations in Java, its types and the built-in annotations available in Java.

Check out the Java training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Mention it in the comments section of this “Annotations in Java” article and we will get back to you as soon as possible.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 1st March,2025

1st March

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR Building Robust Applications with Spring Framework