Java Annotations Tutorial – Types of Java Annotations List For Beginners

Java Annotations Tutorial – Types of Java Annotations List For Beginners from Coding compiler. Here you will learn about Java annotations, types of annotations, annotation retention policy, annotation reflections, built-in annotations. Lean Now.!

Java Annotations Tutorial

Lets start exploring more on java annotations, it’s types, retension policy and built-in annotaions in Java.

  • Java Annotations
  • Java Annotation Retention Policy
  • Java Annotation Reflection
  • Java Comment Defaults
  • Java Built-in Annotations

Java Tutorial – Java Notes

The comment embeds the supplemental information in the source file. The comment does not change the semantics of the program.

Create annotations through an interface-based mechanism.

The following code declares a MyAnno comment named :

// A simple annotation type. 
@interface MyAnno {
  String str();

  int val();
}

@Before the keyword interface. All comments have only method declarations. Comments cannot contain the extends clause.

Java Annotations – Java Note

All annotation types automatically extend the annotation interface. The annotation interface is the super interface for all annotations. The annotation interface is declared in the java.lang.annotation package.

Any type of declaration can have a comment associated with it. For example, you can annotate classes, methods, fields, parameters, and enumeration constants. Comments can also be annotated. In all cases, the comment is before the rest of the statement.

When you apply a comment, you can provide values to its members. For example, here’s MyAnno an example of a class applied to :

// Annotate a method. 
@MyAnno(str = "Annotation Example", val = 100) 
public class Main{}

This comment is linked to the class Main.

Java annotations retention policy

The Java annotations retention policy determines when to discard comments.

Java defines three such strategies: SOURCE, CLASS, and RUNTIME.

  • SOURCE is only kept in the source file and is discarded during compilation.
  • CLASS is stored in the .class file during compilation. It cannot pass the JVM at runtime.
  • RUNTIME is stored in a .class file and can be used by the JVM at runtime.

Specify retention policies for comments by using one of Java’s built-in annotations:

@Retention
Its general form is as follows:

@Retention(retention-policy)

The retention-policy must be SOURCE, CLASSand RUNTIMEone.

The default policy is CLASS.

The following code specifies a retention policy as RUNTIME.

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

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
  String str();

  int val();
}

How to get a comment at runtime by using reflection.

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

// An annotation type declaration. 
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
  String str();

  int val();
}

public class Main {
  @MyAnno(str = "Annotation Example", val = 100)
  public static void myMeth() {
    Main ob = new Main();
    try {
      Class c = ob.getClass();
      Method m = c.getMethod("myMeth");
      MyAnno anno = m.getAnnotation(MyAnno.class);
      System.out.println(anno.str() + " " + anno.val());
    } catch (NoSuchMethodException exc) {
      System.out.println("Method Not Found.");
    }
  }
  public static void main(String args[]) {
    myMeth();
  }
}

Java annotation reflection

You can get all the annotation items that have a RUNTIME reservation associated with an item by calling the item’s getAnnotations().

It has this general form:

Annotation[ ] getAnnotations( )

The following code shows how to get a comment from a class.

import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
  String str();

  int val();
}

@Retention(RetentionPolicy.RUNTIME)
@interface What {
  String description();
}

@What(description = "An annotation")
@MyAnno(str = "Meta2", val = 99)
public class Main {
  @What(description = "test method")
  @MyAnno(str = "Testing", val = 100)
  public static void myMeth() throws Exception {
    Main ob = new Main();
    Annotation annos[] = ob.getClass().getAnnotations();
    System.out.println("All annotations for Meta2:");
    for (Annotation a : annos) {
      System.out.println(a);
    }
    Method m = ob.getClass().getMethod("myMeth");
    annos = m.getAnnotations();
    for (Annotation a : annos) {
      System.out.println(a);
    }

  }

  public static void main(String args[]) throws Exception {
    myMeth();
  }
}

Java comment defaults

You can give the comment member a default value. If you do not specify a value when you apply a comment, these default values are used.

Specify a default value by adding a default clause to the member declaration.

It has this general form:

type member( ) default value;

Here is the @MyAnnorewrite to include the default values:

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
  String str() default "Testing";

  int val() default 9000;
}

Any value or both can be given if needed. Therefore, the following are four ways you can use @MyAnno:

@MyAnno() // both str and val default 
@MyAnno(str = "string") // val defaults 
@MyAnno(val = 100) // str defaults 
@MyAnno(str = "Testing", val = 100) // no defaults

The following program demonstrates the use of default values in comments.

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


@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
  String str() default "Testing";

  int val() default 1;
}

public class Main {
  @ MyAnno ()
  public static void myMeth() throws Exception{
    Main ob = new Main();
      Class c = ob.getClass();
      Method m = c.getMethod("myMeth");
      MyAnno anno = m.getAnnotation(MyAnno.class);
      System.out.println(anno.str() + " " + anno.val());
  }

  public static void main(String args[]) throws Exception{
    myMeth();
  }
}

Java Tutorial – Java Built-in Annotations

Here you will learn about Java built-in annotations.

Java Built-in Comment

Java defines a lot of built-in annotations. Most are specialized, but seven are generic.

Types of Java Annotations

  1. @Retention
  2. @Documented
  3. @Target
  4. @Inherited
  5. @Override
  6. @Deprecated
  7. @SuppressWarnings

@Retention

@Retention is designed to be used only as a comment for another comment. It specifies retention policies.

@Documented

The @Documented annotation is a tagging interface that informs the tool to annotate tags.

@Target

@TargetComments specify the type of declaration to which comments can be applied.

It is designed to be used only as an annotation for another comment. @Target accepts a parameter, which must be a constant of the ElementType enumeration.

Target constant annotations can be applied

  • ANNOTATION_TYPEAnother comment
  • CONSTRUCTOR Constructor
  • FIELD field
  • LOCAL_VARIABLE Local variables
  • METHOD method
  • PACKAGE package
  • PARAMETER parameter
  • TYPE Class, interface, or enumeration

You can specify one or more of these values in the @Target annotation. To specify multiple values, they must be specified in a parenthesized list. E.g:

@Target( { ElementType.FIELD, ElementType.LOCAL_VARIABLE } )

@Inherited

@InheritedIs a tag comment and can only be used for another comment declaration. It only affects the comments that will be used in the class declaration. @InheritedMake the annotations of the superclass inherited by the subclass.

@Override

@Override is a tag comment that can only be used on methods. Methods that are annotated with @Override must override methods in the superclass.

@Deprecated

@Deprecated is a tag comment. It indicates that the statement is out of date and has been replaced by a newer form.

@SuppressWarnings

@SuppressWarningsSpecifies that one or more warnings that may be issued by the compiler are suppressed. The warning to be prohibited is specified by name as a string. This comment can be applied to any type of claim.

Related Java Tutorials & Interview Questions

Related Java Tutorials & Interview Questions
Introduction to Java Programming Java Exceptions Tutorial For Beginners
Java Keywords Tutorial For Beginners Core Java Multiple Choice Questions
Java Data Types Tutorial For Beginners 21 Aricent Java Interview Questions
Java Operators Tutorial For Beginners 53 Accenture Java Interview Questions
Java Control Flow Statements Tutorial 399 Core Java Interview Questions
Java Performance Tuning Tips 581 Advanced Java Interview Questions
Java Class Tutorial For Beginners 60 Java Multiple Choice Questions And Answers

Leave a Comment