Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Java Annotations

Last Updated on January 30, 2023 by Sumit Kumar

In this article, we will learn about Java Annotations, and various formats of Java Annotations. We will also learn about Types of Java Annotations and various different Predefined and meta-annotations present in Java. In the end, we will discuss some of the uses of Java Annotations.

What are Java Annotations

Java Annotations are a type of metadata, that offers information about a program that isn’t included in the actual program. There is no immediate impact of java annotations on the functionality of the code they are applied to.
Java Annotations are used to provide supplementary information about a specific block of the program.

Points to Remember about Java Annotations

Some important points about Java Annotations which we must remember are listed below:

  • Java Annotations begin with a "@"
  • Java Annotations do not affect how a built program behaves.
  • Since Java annotations can affect the way how the program is treated by the compiler, they are much different from the comments
  • Java Annotations are essentially used to offer extra information as an alternative to XML and Java Marker Interfaces.

Basics of Java Annotations

Java Annotations are written using a “@” symbol and can looks like this:

@Entity

An example using the Override Annotation:

@Override
void methodName(){
    //Statements
}

The Java SE API’s java.lang and java.lang.annotation packages contain types that can be used as annotation types. Override and SuppressWarnings are examples of predefined Java annotations. You may also create your own custom annotation types.

Formats of Java Annotations

Java Annotations can be broadly divided into the following 5 types on the basis of the formats they use:

1. Marker Annotations

This type of java annotation is generally used to mark a declaration.. It does not contain any data or any members.

Example:

@Override

2. Single Values Annotations

These annotations have just one member and let you specify the member’s value in a concise manner. When the annotation is applied, we simply need to give the member’s value, although the name of the member is not necessary.

Example:

@TestAnnotation("testing")

3. Full Annotations

These Full Annotations contain multiple elements as parameters, which are separated by commas.

Example:

@TestAnnotation(name= "PrepBytes", value="899")

4. Type Annotations

The Type Annotations in Java are applied to places where a type is being used and is usually declared annotated using @Target annotation.

Example:

@Target(ElementType.TYPE_USE)

5. Repeating Annotations

In Java, the "@RepeatedTest" annotation is used to specify that a test method should be repeated a certain number of times. This annotation is part of the JUnit 5 library and is used in conjunction with the "@Test" annotation. The number of repetitions can be specified as an attribute of the "@RepeatedTest" annotation.

Types of Java Annotations

Various different types of Java Annotations are given below:

1. Predefined Java Annotations

Some Predefined Java Annotations are described below in detail. These are declared in java.lang package.

  • @Deprecated
    In Java, the @Deprecated annotation is used to indicate that a particular program element (such as a class, method, or field) is no longer recommended for use and may be removed in a future version. When the Java compiler encounters an element that has been marked as @Deprecated, it will generate a warning to the developer. Here is an example of how to use these java annotations.

    public class DeprecatedTest{
        @Deprecated
        public void Display(){
            System.out.println("Deprecated method");
        }
    
        public static void main(String args[])
        {
            DeprecatedTest d = new DeprecatedTest();
            d.Display();
        }
    }
  • @Override
    We use this java annotation to indicate that a method in the child class is being overridden. By doing this, you may make your code more legible and prevent maintenance problems like the compiler throwing a compilation error if you change the method signature of the parent class without also altering the signature in the child classes (where this annotation is utilized).it is hard to track this, if we don’t use this java annotation.

    class Base {
        // overridden method
        public void display(){
        	System.out.println("Base Class");
        }
    }
    
    class Derived extends Base {
        // overriding method
        @Override
        public void display(){
        	System.out.println("Derived Class");
        }
    }
    
    class Main {
        public static void main(String[] args) {
        	Derived obj = new Derived();
        	obj.display();
        }
    }

    Output:

    Derived Class

    In the above example code, we have used @Override annotation, which tells the compiler that the method is overriding the method present in the base Class.

  • @SupressWarnings
    In Java, the @SuppressWarnings annotation can be used to suppress specific warnings that the compiler generates. The annotation takes a single argument, which is a string specifying the type of warning to suppress.
    This annotation can be applied to a class, method, or variable. It is important to note that using this annotation may mask important issues in your code, and should be used with caution.

    Example:

    @SuppressWarnings("deprecated")
  • @SafeVarags
    In Java, the @SafeVarargs annotation can be used to indicate that a method or constructor is safe to call with a variable number of arguments of a generic type. This annotation tells the compiler that the method or constructor will not cause any heap pollution, which occurs when a variable of a parameterized type refers to an object that is not of that type.

  • @FunctionalInterface
    In Java, the @FunctionalInterface annotation is used to indicate that an interface is a functional interface. A functional interface is an interface that has only one abstract method. In other words, it is an interface that can be used as the target type of a lambda expression.

    Example:

    @FunctionalInterface
    public interface MyDemoFuncInterface{
      public void myMethod(); // this is an abstract method
    }

2. Meta-Annotations in Java

In Java, meta-annotations are annotations that are used to provide information about other annotations. These meta-annotations are defined in the java.lang.annotation package and they include

  • @Retention
    In Java, the @Retention annotation is used to specify the retention policy of an annotation. The retention policy determines when the annotation is available to the Java Virtual Machine (JVM) and when it is discarded.

    There are three possible retention policies:

    • RetentionPolicy.SOURCE: The annotation is retained only in the source code and is not included in the class files. This is the default retention policy.
    • RetentionPolicy.CLASS: The annotation is retained in the class files but is not available at runtime. This is useful for annotations that are used by the Java compiler but are not needed at runtime.
    • RetentionPolicy.RUNTIME: The annotation is retained in the class files and is available at runtime. This is useful for annotations that are used by both the Java compiler and by Java code at runtime.

    Syntax:

    @Retention(RetentionPolicy)
  • @Documented
    In Java, the @Documented annotation is used to indicate that annotation should be included in the JavaDoc documentation.

    Syntax:
    @Documented

  • @Target
    In Java, the @Target annotation is used to specify the target elements that an annotation type that can be applied. The target elements are the parts of a Java program to which an annotation type can be applied.

    There are several possible elements that an annotation can be applied to

    • ElementType.TYPE: Classes, interfaces, enums, and annotation types
    • ElementType.FIELD: Fields, including enum constants
    • ElementType.METHOD: Methods, including constructors
    • ElementType.PARAMETER: Parameters of a method or constructor
    • ElementType.CONSTRUCTOR: Constructors
    • ElementType.LOCAL_VARIABLE: Local variables
    • ElementType.ANNOTATION_TYPE: Annotation types
    • ElementType.PACKAGE: Package declarations

    Syntax:
    @Target(ElementType)

  • @Inherited
    The "@Inherited" annotation in Java is a built-in annotation that indicates that an annotation type is automatically inherited. If an annotation type is marked with the "@Inherited" meta-annotation, and a class is annotated with that type, then any subclass of that class will have the annotation inherited, unless overridden.

    Syntax:
    @Inherited

  • @Repeatable
    In Java, the @Repeatable annotation is used to indicate that an annotation type can be applied more than once to the same element or type.

3. Custom Java Annotations

We can also create Custom Java Annotations. The syntax for Custom Java Annotations is as given below:

Syntax:

[Access Specifier] @interface
{         
   DataType () [default value];
}
  • By utilizing @interface and the annotation name, annotations may be constructed.
  • The annotation may contain components that resemble methods but do not actually implement any of them.
  • The default setting is not required. There can’t be a null value for the arguments.
  • The method’s return type might be an array of these kinds, a primitive, an enum, a string, or a class name.

Uses of Java Annotations

Java Annotations have a number of uses. Some basic uses are explained below:

  • Giving Instructions to Compiler: Java Annotations can be used to give Instructions to the Compiler, Suppress Warnings, and detect Errors.
  • Deployment-Time and Compile-Time Processing: These annotations’ compile-time instructions enable the software development tools to create code, XML files, and other types of files
  • For Runtime Processing: In order to teach the program at runtime, we may specify annotations to be accessible at runtime. These annotations can be accessed via Java reflection.

Summary
Java annotations are a way to provide metadata about a program, which can be processed by the compiler or other tools. They are similar to comments but are designed to be read by the compiler, rather than by humans. Annotations can be used to indicate that a certain method should be overridden, to provide information about the author of a class, or to indicate that a field should be serialized. They can also be used to provide information to other tools, such as dependency injection frameworks or testing libraries. Java annotations are declared using the "@" symbol and can be placed before class, method, and field declarations.

Leave a Reply

Your email address will not be published. Required fields are marked *