Java

Java – Annotations Tutorial With Examples

Despite not being a part of the program itself, Java Annotations let us include metadata data into our source code. From JDK 5, annotations were introduced to the Java code. No direct impact of annotations on the functionality of the code they are made to (i.e. it does not affect the execution of the program).

We’ll go through how to use annotations, how to apply them, what kinds of preset annotations are available in Java, and how to make your own annotations in this lesson.

What’s the use of Annotations?

1) Guidelines for the compiler: Java has three built-in annotations (@Deprecated, @Override, & @SuppressWarnings) that may be used to provide the compiler specific instructions. For instance, the @override annotation tells the compiler that the annotated method overrides the original method. In the next parts of this post, we’ll talk more about these built-in annotations and provide examples.

2) Compile-time instructors: Annotations may provide the compiler compile-time instructions that can then be utilized by software development tools to generate code, XML files, and other types of files.

A program may be given instructions at runtime by utilizing runtime annotations, which we can declare to be accessible at runtime and which we can access via Java reflection. Later in the same piece, we shall examine this with the aid of an example.

Annotations basics

An annotation always begins with the character @ and is then given a name. The compiler can tell that this is an annotation because of the symbol @.

For instance, the @Override Here @ sign indicates that this is an annotation, and the name of this annotation is Override.

Where may annotations be used?
It is possible to annotate classes, interfaces, methods, and fields. As an example, the procedure is using the annotation below.

@Override
void myMethod() { 
    //Do something 
}

In summary, this annotation tells the compiler that myMethod() is an overriding method that is overriding the method (myMethod()) of the super class. What precisely this annotation is doing in this case is discussed in the following section.

Java has three built-in annotations:

  • @Override
  • @Deprecated
  • @SuppressWarnings

1) @Override:

Use this 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). When you don’t utilize this annotation, it is challenging to track this.

Example:

public class MyParentClass {

    public void justaMethod() {
        System.out.println("Parent class method");
    }
}


public class MyChildClass extends MyParentClass {

    @Override
    public void justaMethod() {
        System.out.println("Child class method");
    }
}

2) @Deprecated

The annotation @Deprecated signifies that the designated element (class, method, or field) is no longer supported and should not be utilized. Every time a program makes use of a method, class, or field that has previously been annotated with the @Deprecated annotation, the compiler issues a warning. The following example demonstrates how the Javadoc @deprecated tag should be used to document deprecated elements. Note the difference in case between @Deprecated and @deprecated. For purposes of documentation, @deprecated is used.

Example:

/**
 * @deprecated
 * reason for why it was deprecated
 */
@Deprecated
public void anyMethodHere(){
    // Do something
}

3) @SuppressWarnings

This annotation tells the compiler to disregard certain warnings. For instance, in the code below, I am using a deprecated function that is tagged with the @Deprecated annotation, which should cause the compiler to provide a warning. However, I am using the @@SuppressWarnings annotation, which would suppress the deprecation warning.

@SuppressWarnings("deprecation")
    void myMethod() {
        myObject.deprecatedMethod();
}

Creating Custom Annotations

As illustrated in the sample below, annotations are made by using @interface, followed by the annotation name.
Additionally, an annotation may contain components. They seem like techniques. For instance, there are four pieces in the code below. We shouldn’t provide this items implementation.
The Java.lang.annotation class extends all annotations.
interface for annotations. Any extends clauses are not permitted in annotations.

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
@Documented
@Target(ElementType.METHOD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation{
    int studentAge() default 18;
    String studentName();
    String stuAddress();
    String stuStream() default "CSE";
}

Note: When utilizing annotation, all the components whose default values have already been defined may be skipped. For instance, if I were to add the aforementioned annotation to a class, I would do it as follows:

@MyCustomAnnotation(
    studentName="Chaitanya",
    stuAddress="Agra, India"
)
public class MyClass {
...
}

As you can see, we have left the studentAge and stuStream components empty since setting their values is optional (default values already been set in Annotation definition, but if you want you can assign new value while using annotation just the same way as we did for other elements). However, while using annotation, we must provide the values for other components (the ones without default values defined).

Note that array elements are also compatible with annotations. What we can do with them is this:
Definition of an annotation

@interface MyCustomAnnotation {
    int      count();
    String[] books();
}

Usage:

@MyCustomAnnotation(
    count=3,
    books={"C++", "Java"}
)
public class MyClass {

}

@Documented

The annotation @Documented specifies that components containing this annotation should have JavaDoc documentation. For instance:

java.lang.annotation.Documented
@Documented
public @interface MyCustomAnnotation {
  //Annotation body
}
@MyCustomAnnotation
public class MyClass { 
     //Class body
}

The annotation @MyCustomAnnotation would be added in the MyClass class’s Java documentation when it is generated.

@Target

It specifies where we can use the annotation. For example: In the below code, we have defined the target type as METHOD which means the below annotation can only be used on methods.

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

@Target({ElementType.METHOD})
public @interface MyCustomAnnotation {

}
public class MyClass {
   @MyCustomAnnotation
   public void myMethod()
   {
       //Doing something
   }
}

Note:

1) If you don’t declare any Target types, any element may get an annotation.
2) An annotation may contain the following potential Target values in addition to ElementType.METHOD.

ElementType.METHOD
ElementType.PACKAGE
ElementType.PARAMETER
ElementType.TYPE
ElementType.ANNOTATION_TYPE
ElementType.CONSTRUCTOR
ElementType.LOCAL_VARIABLE
ElementType.FIELD

@Inherited

A custom annotation used in a class should be inherited by all of its child classes, according to the @Inherited annotation. For instance:

java.lang.annotation.Inherited

@Inherited
public @interface MyCustomAnnotation {

}
@MyCustomAnnotation
public class MyParentClass { 
  ... 
}
public class MyChildClass extends MyParentClass { 
   ... 
}

Here, the annotation @MyCustomAnnotation, which is designated with the @inherited annotation, is used by the class MyParentClass. It denotes that the @MyCustomAnnotation is inherited by the subclass MyChildClass.

@Retention

It specifies the retention period for annotations of the annotated type.

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

@Retention(RetentionPolicy.RUNTIME)
@interface MyCustomAnnotation {
    
}

RetentionPolicy was utilized in this instance.

RUNTIME. There are also two other choices. Let’s look at what they mean:
RetentionPolicy.
RUNTIME: The annotation need to be accessible at runtime for Java reflection analysis.
RetentionPolicy.
CLASS: Although the annotation is in the.class file, it is not accessible during runtime.
RetentionPolicy.
SOURCE: The annotation would be present in the program’s source code; it wouldn’t be seen in a.class file or at runtime.

That concludes the discussion of “Java Annotation.” Please feel free to ask any inquiries by using the form below.

 

 

Related Articles

Leave a Reply

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

Back to top button