Inherited Annotations in Java
Last Updated :
09 Aug, 2022
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());
}
}
}
Outputnull
@CustomAnnotation(value="Sky is limitless")
Name of the annotation : interface CustomAnnotation
Value : Sky is limitless
Similar Reads
Annotations in Java
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.A
9 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 ann
2 min read
Inheritance and Constructors in Java
Constructors in Java are used to initialize the values of the attributes of the object serving the goal to bring Java closer to the real world. We already have a default constructor that is called automatically if no constructor is found in the code. But if we make any constructor say parameterized
3 min read
Hibernate - @Inheritance Annotation
The @Inheritance annotation in JPA is used to specify the inheritance relation between two entities. It is used to define how the data of the entities in the hierarchy should be stored in the database. The @Inheritance annotation provides us with benefits to reduce code complexity by creating a bas
6 min read
Comparison of Inheritance in C++ and Java
The purpose of inheritance is the same in C++ and Java. Inheritance is used in both languages for reusing code and/or creating an âis-aâ relationship. The following examples will demonstrate the differences between Java and C++ that provide support for inheritance. 1) In Java, all classes inherit fr
4 min read
Delegation vs Inheritance in Java
Inheritance in Java programming is the process by which one class takes the property of another other class. i.e. the new classes, known as derived or child class, take over the attributes and behavior of the pre-existing classes, which are referred to as base classes or super or parent class.Delega
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
7 min read
Why Constructors are not inherited in Java?
Constructor is a block of code that allows you to create an object of class and has same name as class with no explicit return type. Whenever a class (child class) extends another class (parent class), the sub class inherits state and behavior in the form of variables and methods from its super clas
2 min read
The @Deprecated Annotation in Java
The @Deprecated annotation tells the compiler that a method, class, or field is deprecated and that it should generate a warning if someone tries to use it. That's what a deprecated class or method is. It's no longer relevant. It is so unimportant that you should stop using it because it has been su
5 min read
Inheritance in Java
Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
14 min read