The Wayback Machine - https://web.archive.org/web/20240907091724/https://www.geeksforgeeks.org/annotations-in-java/
Open In App

Annotations in Java

Last Updated : 25 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Annotations are used to provide supplemental information about a program. 

  • Annotations start with ‘@’.
  • Annotations do not change the action of a compiled program.
  • Annotations help to associate metadata (information) to the program elements i.e. instance variables, constructors, methods, classes, etc.
  • Annotations are not pure comments as they can change the way a program is treated by the compiler. See below code for example.
  • Annotations basically are used to provide additional information, so could be an alternative to XML and Java marker interfaces.

Hierarchy of Annotations in Java 

Image

Implementation:

Note: This program throws compiler error because we have mentioned override, but not overridden, we have overloaded display.

Example:

Java




// Java Program to Demonstrate that Annotations
// are Not Barely Comments
 
// Class 1
class Base {
   
    // Method
    public void display()
    {
        System.out.println("Base display()");
    }
}
 
// Class 2
// Main class
class Derived extends Base {
   
    // Overriding method as already up in above class
    @Override public void display(int x)
    {
        // Print statement when this method is called
        System.out.println("Derived display(int )");
    }
 
    // Method 2
    // Main driver method
    public static void main(String args[])
    {
        // Creating object of this class inside main()
        Derived obj = new Derived();
 
        // Calling display() method inside main()
        obj.display();
    }
}


Output: 

10: error: method does not override or implement
    a method from a supertype

If we remove parameter (int x) or we remove @override, the program compiles fine. 

Categories of Annotations

There are broadly 5 categories of annotations as listed:

  1. Marker Annotations
  2. Single value Annotations
  3. Full Annotations
  4. Type Annotations
  5. Repeating Annotations

Let us discuss and we will be appending code wherever required if so. 

Category 1: Marker Annotations

The only purpose is to mark a declaration. These annotations contain no members and do not consist of any data. Thus, its presence as an annotation is sufficient. Since the marker interface contains no members, simply determining whether it is present or absent is sufficient. @Override is an example of Marker Annotation. 

Example

@TestAnnotation()

Category 2: Single value Annotations 

These annotations contain only one member and allow a shorthand form of specifying the value of the member. We only need to specify the value for that member when the annotation is applied and don’t need to specify the name of the member. However, in order to use this shorthand, the name of the member must be a value. 

Example

@TestAnnotation(“testing”);

Category 3: Full Annotations 

These annotations consist of multiple data members, names, values, pairs. 

Example

@TestAnnotation(owner=”Rahul”, value=”Class Geeks”)

Category 4: Type Annotations 

These annotations can be applied to any place where a type is being used. For example, we can annotate the return type of a method. These are declared annotated with @Target annotation.

Example

Java




// Java Program to Demonstrate Type Annotation
 
// Importing required classes
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
 
// Using target annotation to annotate a type
@Target(ElementType.TYPE_USE)
 
// Declaring a simple type annotation
@interface TypeAnnoDemo{}
 
// Main class
public class GFG {
   
    // Main driver method
    public static void main(String[] args) {
 
        // Annotating the type of a string
        @TypeAnnoDemo String string = "I am annotated with a type annotation";
        System.out.println(string);
        abc();
    }
 
    // Annotating return type of a function
    static @TypeAnnoDemo int abc() {
       
        System.out.println("This function's  return type is annotated");
       
        return 0;
    }
}


Output: 

I am annotated with a type annotation
This function's  return type is annotated

 

Category 5: Repeating Annotations 

These are the annotations that can be applied to a single item more than once. For an annotation to be repeatable it must be annotated with the @Repeatable annotation, which is defined in the java.lang.annotation package. Its value field specifies the container type for the repeatable annotation. The container is specified as an annotation whose value field is an array of the repeatable annotation type. Hence, to create a repeatable annotation, firstly the container annotation is created, and then the annotation type is specified as an argument to the @Repeatable annotation.

Example:

Java




// Java Program to Demonstrate a Repeatable Annotation
 
// Importing required classes
import java.lang.annotation.Annotation;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
 
// Make Words annotation repeatable
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(MyRepeatedAnnos.class)
@interface Words
{
    String word() default "Hello";
    int value() default 0;
}
 
// Create container annotation
@Retention(RetentionPolicy.RUNTIME)
@interface MyRepeatedAnnos
{
    Words[] value();
}
public class Main {
 
    // Repeat Words on newMethod
    @Words(word = "First", value = 1)
    @Words(word = "Second", value = 2)
    public static void newMethod()
    {
        Main obj = new Main();
 
        try {
            Class<?> c = obj.getClass();
 
            // Obtain the annotation for newMethod
            Method m = c.getMethod("newMethod");
 
            // Display the repeated annotation
            Annotation anno
                = m.getAnnotation(MyRepeatedAnnos.class);
            System.out.println(anno);
        }
        catch (NoSuchMethodException e) {
            System.out.println(e);
        }
    }
    public static void main(String[] args) { newMethod(); }
}


Output: 

@MyRepeatedAnnos(value={@Words(value=1, word="First"), @Words(value=2, word="Second")})

 

 Predefined/ Standard Annotations

Java popularly defines seven built-in annotations as we have seen up in the hierarchy diagram.

  • Four are imported from java.lang.annotation: @Retention, @Documented, @Target, and @Inherited.
  • Three are included in java.lang: @Deprecated, @Override and @SuppressWarnings

Annotation 1: @Deprecated 

  • It is a marker annotation. It indicates that a declaration is obsolete and has been replaced by a newer form.
  • The Javadoc @deprecated tag should be used when an element has been deprecated.
  • @deprecated tag is for documentation and @Deprecated annotation is for runtime reflection.
  • @deprecated tag has higher priority than @Deprecated annotation when both are together used.

Example:

Java




public class DeprecatedTest
{
    @Deprecated
    public void Display()
    {
        System.out.println("Deprecatedtest display()");
    }
 
    public static void main(String args[])
    {
        DeprecatedTest d1 = new DeprecatedTest();
        d1.Display();
    }
}


Output

Deprecatedtest display()

Annotation 2: @Override

It is a marker annotation that can be used only on methods. A method annotated with @Override must override a method from a superclass. If it doesn’t, a compile-time error will result (see this for example). It is used to ensure that a superclass method is actually overridden, and not simply overloaded.

Example

Java




// Java Program to Illustrate Override Annotation
 
// Class 1
class Base
{
     public void Display()
     {
         System.out.println("Base display()");
     }
      
     public static void main(String args[])
     {
         Base t1 = new Derived();
         t1.Display();
     }    
}
 
// Class 2
// Extending above class
class Derived extends Base
{
     @Override
     public void Display()
     {
         System.out.println("Derived display()");
     }
}


Output

Derived display()

Annotation 3: @SuppressWarnings 

It is used to inform the compiler to suppress specified compiler warnings. The warnings to suppress are specified by name, in string form. This type of annotation can be applied to any type of declaration.

Java groups warnings under two categories. They are deprecated and unchecked. Any unchecked warning is generated when a legacy code interfaces with a code that uses generics.

Example:

Java




// Java Program to illustrate SuppressWarnings Annotation
 
// Class 1
class DeprecatedTest
{
    @Deprecated
    public void Display()
    {
        System.out.println("Deprecatedtest display()");
    }
}
 
// Class 2
public class SuppressWarningTest
{
    // If we comment below annotation, program generates
    // warning
    @SuppressWarnings({"checked", "deprecation"})
    public static void main(String args[])
    {
        DeprecatedTest d1 = new DeprecatedTest();
        d1.Display();
    }
}


Output

Deprecatedtest display()

Annotation 4: @Documented 

It is a marker interface that tells a tool that an annotation is to be documented. Annotations are not included in ‘Javadoc’ comments. The use of @Documented annotation in the code enables tools like Javadoc to process it and include the annotation type information in the generated document.

Annotation 5: @Target 

It is designed to be used only as an annotation to another annotation. @Target takes one argument, which must be constant from the ElementType enumeration. This argument specifies the type of declarations to which the annotation can be applied. The constants are shown below along with the type of the declaration to which they correspond.

Target Constant Annotations Can Be Applied To
ANNOTATION_TYPE Another annotation
CONSTRUCTOR Constructor
FIELD Field
LOCAL_VARIABLE Local variable
METHOD Method
PACKAGE Package
PARAMETER Parameter
TYPE Class, Interface, or enumeration

We can specify one or more of these values in a @Targetannotation. To specify multiple values, we must specify them within a braces-delimited list. For example, to specify that an annotation applies only to fields and local variables, you can use this @Target annotation: @Target({ElementType.FIELD, ElementType.LOCAL_VARIABLE}) @Retention Annotation It determines where and how long the annotation is retent. The 3 values that the @Retention annotation can have:

  • SOURCE: Annotations will be retained at the source level and ignored by the compiler.
  • CLASS: Annotations will be retained at compile-time and ignored by the JVM.
  • RUNTIME: These will be retained at runtime.

Annotation 6: @Inherited 

@Inherited is a marker annotation that can be used only on annotation declaration. It affects only annotations that will be used on class declarations. @Inherited causes the annotation for a superclass to be inherited by a subclass. Therefore, when a request for a specific annotation is made to the subclass, if that annotation is not present in the subclass, then its superclass is checked. If that annotation is present in the superclass, and if it is annotated with @Inherited, then that annotation will be returned. 

Annotation 7: User-defined (Custom) 

User-defined annotations can be used to annotate program elements, i.e. variables, constructors, methods, etc. These annotations can be applied just before the declaration of an element (constructor, method, classes, etc). 

Syntax: Declaration

[Access Specifier] @interface<AnnotationName>
{         
   DataType <Method Name>() [default value];
}

Do keep these certain points as rules for custom annotations before implementing user-defined annotations. 

  1. AnnotationName is an interface.
  2. The parameter should not be associated with method declarations and throws clause should not be used with method declaration.
  3. Parameters will not have a null value but can have a default value.
  4. default value is optional.
  5. The return type of method should be either primitive, enum, string, class name, or array of primitive, enum, string, or class name type.

Example:

Java




// Java Program to Demonstrate User-defined Annotations
 
package source;
 
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
 
// User-defined annotation
@Documented
@Retention(RetentionPolicy.RUNTIME)
@ interface TestAnnotation
{
    String Developer() default "Rahul";
    String Expirydate();
} // will be retained at runtime
 
// Driver class that uses @TestAnnotation
public class Test
{
    @TestAnnotation(Developer="Rahul", Expirydate="01-10-2020")
    void fun1()
    {
        System.out.println("Test method 1");
    }
 
    @TestAnnotation(Developer="Anil", Expirydate="01-10-2021")
    void fun2()
    {
        System.out.println("Test method 2");
    }
     
    public static void main(String args[])
    {
        System.out.println("Hello");
    }
}


Output: 

Hello

 



Similar Reads

How to Create Your Own Annotations in Java?
Annotations are a form of metadata that provide information about the program but are not a part of the program itself. An Annotation does not affect the operation of the code they Annotate. Now let us go through different types of java annotations present that are listed as follows: Predefined annotations.: @Deprecated, @Override, @SuppressWarning
5 min read
Inherited Annotations in Java
Annotations in Java help associate metadata to the program elements such as classes, instance variables, methods, etc. Annotations can also be used to attach metadata to other annotations. These types of annotations are called meta-annotation. Java, by default, does not allow the custom annotations to be inherited. @inherited is a type of meta-anno
5 min read
Java @Retention Annotations
In Java, annotations are used to attach meta-data to a program element such as a class, method, instances, etc. Some annotations are used to annotate other annotations. These types of annotations are known as meta-annotations. @Retention is also a meta-annotation that comes with some retention policies. These retention policies determine at which p
3 min read
Java @Documented Annotations
By default, Java annotations are not shown in the documentation created using the Javadoc tool. To ensure that our custom annotations are shown in the documentation, we use @Documented annotation to annotate our custom annotations. @Documented is a meta-annotation (an annotation applied to other annotations) provided in java.lang.annotation package
2 min read
Java - @Target Annotations
Annotations in java are used to associate metadata to program elements like classes, methods, instance variables, etc. There are mainly three types of annotations in java: Marker Annotation (without any methods), Single-Valued Annotation (with a single method), and Multi-Valued Annotation (with more than one method). @Target annotation is a meta-an
3 min read
Hibernate - Annotations
Annotation in JAVA is used to represent supplemental information. As you have seen @override, @inherited, etc are an example of annotations in general Java language. For deep dive please refer to Annotations in Java. In this article, we will discuss annotations referred to hibernate. So, the motive of using a hibernate is to skip the SQL part and f
7 min read
Spring Framework Annotations
Spring framework is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. Now talking about Spring Annotation, Spring Ann
5 min read
Spring Core Annotations
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. In the Spring framework, the annotations are classified into diffe
4 min read
Difference Between @Component, @Repository, @Service, and @Controller Annotations in Spring
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. Here, we are going to discuss the difference between the 4 most im
4 min read
Spring Boot Annotations - @JmsListener, @Retryable, @RSocketMessageMapping, @ConstructorBinding, and @Slf4j
Spring Boot is a popular framework for building modern, scalable, and efficient Java applications. One of the key features of Spring Boot is its extensive use of annotations, which simplify the process of configuring and deploying Spring-based applications. In this article, we will explore some of the latest Spring Boot annotations and how they can
7 min read
Spring Boot - @PathVariable and @RequestParam Annotations
When building RESTful APIs with Spring Boot, it's crucial to extract data from incoming HTTP requests to process and respond accordingly. The Spring framework provides two main annotations for this purpose: @PathVariable and @RequestParam. The @PathVariable annotation is used to retrieve data from the URL path. By defining placeholders in the reque
8 min read
Spring Bean Validation - JSR-303 Annotations
In this article, we'll explore practical examples of how to apply JSR-303 annotations to your domain objects from basic annotations to advanced. So basically annotations provide a declarative way to configure Spring beans, manage dependencies, and define behaviors, reducing the need for boilerplate code and making your code more concise and express
6 min read
Spring - Stereotype Annotations
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. Now talking about Spring Annotation, Spring Annotations a
10 min read
Spring Boot - Annotations
Spring Boot Annotations are a form of metadata that provides data about a spring application. Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead
8 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
java.lang.Math.atan2() in Java
atan2() is an inbuilt method in Java that is used to return the theta component from the polar coordinate. The atan2() method returns a numeric value between -[Tex]\pi [/Tex]and [Tex]\pi [/Tex]representing the angle [Tex]\theta [/Tex]of a (x, y) point and the positive x-axis. It is the counterclockwise angle, measured in radian, between the positiv
1 min read
java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL cl
5 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Java Swing | Translucent and shaped Window in Java
Java provides different functions by which we can control the translucency of the window or the frame. To control the opacity of the frame must not be decorated. Opacity of a frame is the measure of the translucency of the frame or component. In Java, we can create shaped windows by two ways first by using the AWTUtilities which is a part of com.su
5 min read
Java lang.Long.numberOfTrailingZeros() method in Java with Examples
java.lang.Long.numberOfTrailingZeros() is a built-in function in Java which returns the number of trailing zero bits to the right of the lowest order set bit. In simple terms, it returns the (position-1) where position refers to the first set bit from the right. If the number does not contain any set bit(in other words, if the number is zero), it r
3 min read
Java lang.Long.numberOfLeadingZeros() method in Java with Examples
java.lang.Long.numberOfLeadingZeros() is a built-in function in Java which returns the number of leading zero bits to the left of the highest order set bit. In simple terms, it returns the (64-position) where position refers to the highest order set bit from the right. If the number does not contain any set bit(in other words, if the number is zero
3 min read
Article Tags :
Practice Tags :