Open In App

Inherited Annotations in Java

Last Updated : 09 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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-annotation used to annotate custom annotations so that the subclass can inherit those custom annotations. The syntax to use @inherited annotation is mentioned below.

@Inherited
@interface CustomAnnotation {
    String value () default "GFG";
}

Scenarios:

Below we will be discussing both the scenarios:

  • Case 1: Using @Inherited annotation
  • Case 2: Without using @inherited Annotation

Now let us discuss both the scenarios and implement the same as a java program to get a better understanding of the same.

Case 1: Using @Inherited annotation

In the code example shown below, we have created a custom annotation named CustomAnnotation and annotated it with @Inherited annotation. We used the CustomAnnotation to annotate the Super class which is Inherited by InheritedAnnotationDemo class. InheritedAnnotationDemo also inherits the CustomAnnotation as it is annotated using @Inherited annotation. 

Example 

Java




// Java Program to Illustrating Use of Custom Annotations
// With @inherited annotation
 
// Importing required classes from java.lang package
import java.lang.annotation.*;
import java.lang.reflect.AnnotatedElement;
 
// Creating our single valued custom annotation
// with @inherited annotation
@Inherited
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
 
// Custom annotation
@interface CustomAnnotation
{
    String value() default "GFG";
}
 
// Annotating the super class using
// the custom annotation
@CustomAnnotation(value = "Sky is limitless")
 
// Class 1
// Parent
class Super {
}
 
// Class 2
// Child class
// This is our derived class which inherits the
// Super class and the custom annotation
public class InheritedAnnotationDemo extends Super {
 
    // Method 1
    // Main driver method
    public static void main(String[] arg) throws Exception
    {
 
        // Printing the annotation used to annotated the
        // Super and InheritedAnnotationDemo classes
        System.out.println(
            new InheritedAnnotationDemo()
                .getClass()
                .getAnnotation(CustomAnnotation.class));
 
        System.out.println(
            new Super().getClass().getAnnotation(
                CustomAnnotation.class));
 
        // Obtaining the class class name and
        // printing the annotation info about the
        //  annotation info attached to the Super class
        Class obj = Super.class;
 
        // Calling the method 2 to
        // print the annotation states
        printAnnotationState(obj);
    }
 
    // Method 2
    // To print the annotation state
    static void printAnnotationState(AnnotatedElement ann)
    {
 
        // Obtaining all the annotations attached to the
        // passed element and storing it in an array
        Annotation[] annotationsArray
            = ann.getAnnotations();
 
        // Iterating on all the annotations stored inside of
        // the array above and printing their information
        for (Annotation annotation : annotationsArray) {
 
            // Print and display nameand value of annotation
            System.out.println(
                "Name of the annotation : "
                + annotation.annotationType());
            System.out.println(
                "Value : "
                + ((CustomAnnotation)annotation).value());
        }
    }
}


Output

@CustomAnnotation(value="Sky is limitless")
@CustomAnnotation(value="Sky is limitless")
Name of the annotation : interface CustomAnnotation
Value : Sky is limitless

Case 2: Without using @inherited Annotation

In the code example mentioned below everything the same except that we haven’t used @Inherited annotation to annotate our CustomAnnotation. Due to this, the CustomAnnotation is not inherited by the InheritedAnnotationDemo class. So, when we use getAnnotation() method for InheritedAnnotationDemo class it does not return CustomAnnotation. In this case, where we haven’t used any annotation to annotate InheritedAnnotationDemo class it simply returns null.

Example :

Java




// Java Program to Illustrating Use of Custom Annotations
// Without @inherited annotation
 
// Importing required classes from java.lang package
import java.lang.annotation.*;
import java.lang.reflect.AnnotatedElement;
 
// Creating our single valued custom
// annotation without @inherited annotation
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
// Custom annotation
@interface CustomAnnotation
{
    String value() default "GFG";
}
 
// Annotating the super class using our
// custom annotation
@CustomAnnotation(value = "Sky is limitless")
 
// Class 1
class Super {
}
 
// Class 2
// Main class
// This is our derived class which inherits the
// Super class but does not inherit the
// CustomAnnotation
public class InheritedAnnotationDemo extends Super {
    public static void main(String[] arg) throws Exception
    {
 
        // Printing the annotation used to annotated the
        // Super and InheritedAnnotationDemo classes
        System.out.println(
            new InheritedAnnotationDemo()
                .getClass()
                .getAnnotation(CustomAnnotation.class));
 
        // As we haven't used the @Inherited Annotation to
        // create the custom annotation therefore not
        // inherited by InheritedAnnotationDemo class. When
        // we use getAnnotation() now, returns null.
        System.out.println(
            new Super().getClass().getAnnotation(
                CustomAnnotation.class));
 
        // Obtaining the class class name and
        // printing the annotation info about the annotation
        // info attached to the Super class
        Class obj = Super.class;
 
        // Calling the Method 2 to
        // print the annotation state
        printAnnotationState(obj);
    }
 
    // Method 2
    // To print the annotation state
    static void printAnnotationState(AnnotatedElement ann)
    {
 
        // Obtaining all the annotations attached to the
        // passed element and storing it in an array
        Annotation[] annotationsArray
            = ann.getAnnotations();
 
        // Iterating on all the annotations stored inside of
        // the array above and printing their information
        for (Annotation annotation : annotationsArray) {
 
            // Print and display name and value of the
            // annotation
            System.out.println(
                "Name of the annotation : "
                + annotation.annotationType());
            System.out.println(
                "Value : "
                + ((CustomAnnotation)annotation).value());
        }
    }
}


Output

null
@CustomAnnotation(value="Sky is limitless")
Name of the annotation : interface CustomAnnotation
Value : Sky is limitless

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads