7
Most read
8
Most read
9
Most read
Annotations in Java with Example
In this article, we will learn about annotations in Java with syntax and examples.
Annotations in Java
The annotations represent the metadata i.e attached with the class, interface,
function, or fields to denote a few additional information. The Java compiler and the
JVM use this information during processing.
Annotations in Java provide added information that can be used as an alternative
option for XML and Java marker interfaces.These are not a part of the Java
program, yet they provide access to add metadata information into the course code.
Java introduced the concept of annotations from JDK5.
As mentioned earlier, annotations provide only supplemental details about a
program. It does not affect the operation of the code they annotate.
More on java annotations:
■ They start with the symbol ‘@’.
■ Annotations do not modify the action or executions of a compiled program
like its classes, variables, constructors, interfaces, methods, and many
more.
■ We cannot consider them as mere comments. This is because
annotations change the method a compiler treats a program.
Built-in Java annotations:
Before getting into custom or user-defined annotations, let us take a look at the
built-in Java annotations. Some of the below-given annotations are applied to Java
code and the rest are applied to other annotations.
Built-in Java Annotations in Java code:
■ @Override
■ @SuppressWarnings
■ @Deprecated
Built-in Java Annotations used in other annotations:
■ @Target
■ @Retention
■ @Inherited
■ @Documented
Built-in Java Annotations
Let us look at a brief description of the built-in annotations.
1. @Override:
The @Override annotation makes sure that the subclass method overrides the
parent class method. If this is not the case, it throws an error during compilation. It is
easy to get rid of careless mistakes like spelling mistakes by marking the @Override
annotation. It gives assurance that the method is overridden.
Sample program to implement @Overrided annotation:
class FirstCode{
void learnCourse(){
System.out.println("Learn Courses with FirstCode");
}}
class FirstCode2 extends FirstCode{
@Override
void learnCourse(){
System.out.println("Learn Java with FirstCode");
}}
class FirstCodeMain{
public static void main(String args[]){
FirstCode fc = new FirstCode2();
fc.learnCourse();
}
}
Output:
Compile Time Error
2. @SuppressWarnings:
This annotation suppresses the warning that the compiler issues.
Sample program to implement @SuppressWarning annotation:
import java.util.*;
class FirstCode{
@SuppressWarning("unchecked")
public static void main(String args[]){
ArrayList al = new ArrayList();
al.add("Java");
al.add(C++);
al.add("Python");
for(Object obj:al)
System.out.println(obj);
}
}
Output:
Now no warning at compile time
Once we remove the @SuppressWarning(“unchecked”) annotation, the compiler
shows a warning due to the usage of non-generic collections.
3. @Deprecated:
The @Deprecated annotation denotes that the particular method is deprecated, so
the compiler prints the warning message. It also notifies the user that it may be
eradicated in future versions. Therefore, it is good to avoid such methods.
Sample program to implement @deprecated annotation:
class FirstCode{
void course1(){
System.out.println("Learn Java with FirstCode");
}
@Deprecated
void course2(){
System.out.println("Learn C++ with FirstCode");
}}
class FirstCodeMain{
public static void main(String args[]){
Firstcode fc = new FirstCode();
fc.course2();
}
}
Output:
During compilation:Note: Test.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
During Runtime:
Learn C++ with FirstCode
4. @Documented:
It is a marker interface that informs a toll that an annotation is to be documented. As
the annotations are not provided in the ‘Javadoc’ comments, the @Documented
annotation takes care of it. It enables the tools like ‘Javadoc’ to include and process
the annotation that is given in the document.
5. @Target:
It is designed to use as an annotation to another annotation. @Target takes a
parameter that is a constant from the ElementType enumeration. It denotes the type
of declaration to which we can apply the annotation. The constants given in the
below table are given with the type of the declaration to which it corresponds.
Target Constant Annotations that can be applied to
ANNOTATION_TYPE Another annotation
CONSTRUCTOR Constructor
FIELD Field
LOCAL_VARIABLE Local variable
METHOD Method
PACKAGE Package
PARAMETER Parameter
TYPE Class, Interface, or enumeration
There is flexibility to mention one or more of these values in a @Targetannotation. In
such a case, we can mention them in the braces-delimited list. Eg: To denote an
annotation that applies only to the local variables and fields, we can mention the
@Target annotation as given below:
@Target({Element.Type.FIELD, ElementType.LOCAL_VARIABLE})
6. @Retention Annotation
This denotes where and how long the annotation is retent. This annotation can hold
three values:
SOURCE: Annotations that are retained at the source level and ignored by the
compiler.
CLASS: Annotations that are retained at the source level and ignored by the JVM.
RUNTIME: These annotations will be retained during the runtime.
7. @Inherited:
The @Inherited annotation is a marker that is used to declare annotations. It has
control over the annotations that are used in class declarations. @Inhertited causes
the annotation for a superclass to be inherited by a subclass.
Thus, when a request is made to the subclass and the annotation is absent in the
superclass and annotated with @Inherited, then that annotation will be returned.
@Inherited
@interface FirstCode { }
@interface FirstCode{ }
class Superclass{}
class Subclass extends Superclass{}
Java User-defined annotation:
User-defined annotations or custom annotations can annotate program elements.
These elements include the variables, constructors, methods, etc. They are applied
before the declaration of an element.
Syntax: Declaration of a user-defined annotation:
@interface NewAnnotation
Here, NewAnnotation is the name of the annotation.
Rules to declare user-defined annotation
1. AnnotationName is an interface.
2. The parameter should not be related to the method declarations and throw errors.
3. Null values cannot be assigned to these parameters. But they can have default
values.
4. And these default values are optional.
5. The return type of the method must be either primitive, string, enum, an array of
the primitive, class name, or class name type.
Types of Annotation in Java:
The annotations are classified into five main types:
1. Marker Annotation
2. Single-value Annotation
3. Full Annotation
4. Type Annotation
5. Repeating Annotation
1. Marker Annotation:
This annotation is no method or any data. The only purpose of this annotation is to
mark a declaration. As it has no members, simply determining if it is present or
absent is enough. @Override and @Deprecated are examples for marker
Annotation.
Eg: @interface NewAnnotation{}
2. Single-value annotation:
An annotation with just one method is known as a single-value annotation. It allows
a shorthand form of assigning a value to a variable. All we need to do is, mention the
value for the data member when we apply the annotation. We need not mention the
name of the data member. But to use this shorthand, the name of the member
should be a value.
Snippet to implement single-value annotation:
@interface NewAnnotation{
int value();
}
Snippet to implement single-annotation with default value:
@interface NewAnnotation{
int value() default 0;
}
Example to apply a single-value annotation:
@NewAnnotation(value=5)
3. Full Annotation or Multi-value annotation:
It is the annotation that consists of multiple values, data members, names, and
pairs.
Snippet to implement full annotation:
@interface NewAnnotation{
int value1();
String value2();
String value3();
}
}
Example to implement full annotation with default values:
@interface NewAnnotation{
int value1() default 1;
String value2() default "";
String value3() default "FirstCode";
}
Snippet to implement multi-value annotation:
@NewAnnotation(value1=5, value2="FirstCode",value3="Java")
4. Type Annotation:
We can apply this annotation where a type is present. For example, we can annotate
the return type of a method. These are stated annotated with @Target annotation.
Sample program to implement type annotation:
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target(ElementType.TYPE_USE)
@interface TypeAnnoPgm{}
public class FirstCode{
public static void main(String[] args) {
@TypeAnnoPgm String string = "This string is annotated with a type annotation";
System.out.println(string);
xyz();
}
static @TypeAnnoPgm int xyz() {
System.out.println("The return type of this function is annotated");
return 0;
}
}
Output:
This string is annotated with a type annotation
The return type of this function is annotated
5. Repeating Annotations:
As the name suggests, these annotations can be applied to the same item more
than once. To make the annotation repeatable, we must annotate it with the
@Repeatable annotation as defined in the java.lang.annotation package. The values
in the field mention the contained type for the repeatable annotation. The contained
is mentioned as an annotation whose value field is an array of the repeatable
annotation type.
To make an annotation repeatable, we must first create the container annotation.
And we must mention the annotation type as an argument to the @Repeatable
annotation.
Sample program to implement repeating annotations:
import java.lang.annotation.Annotation;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(MyRepeatedAnnos.class)
@interface Words
{
String word() default "FirstCode";
int value() default 0;
}
@Retention(RetentionPolicy.RUNTIME) // Container annotation creation
@interface MyRepeatedAnnos
{
Words[] value();
}
public class Main {
@Words(word = "First Course = Java", value = 1)
@Words(word = "Second Course = C++", value = 2)
public static void newMethod()
{
Main obj = new Main();
try {
Class c = obj.getClass();
Method m = c.getMethod("newMethod");
Annotation anno = m.getAnnotation(MyRepeatedAnnos.class);
System.out.println(anno);
}
catch (NoSuchMethodException e) {
System.out.println(e);
}
}
public static void main(String[] args) { newMethod(); }
}
Output:
@MyRepeatedAnnos(value={@Words(value=1, word=”First Course”),
@Words(value=2, word=”Second Course”)})
Building annotations in a real-world
scenario:
In reality, a Java programmer only needs to apply the annotation. It is not the task of
the programmer to create or access annotations. These tasks are performed by the
implementation provider. On behalf of the annotation, the Java compiler or the JVM
performs various extra operations too.
Sample program to implement User-defined
annotations:
package source;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@ interface MyAnnotation //user-defined annotations
{
String Developer() default "Programmer1";
String Expirydate();
} // will be retained at runtime
public class FirstCode
{
@MyAnnotation(Developer="Programmer1", Expirydate="01-12-2023")
void fun1()
{
System.out.println("Test method 1");
}
@MyAnnotation(Developer="Progammer2", Expirydate="01-10-2024")
void fun2()
{
System.out.println("Test method 2");
}
public static void main(String args[])
{
System.out.println("Learn Java with FirstCode");
}
}
Output:
Learn Java with FirstCode
Uses of Java Annotations:
1. Provides commands to the compiler:
The built-in annotations help the programmers in giving various instructions to the
compiler. For example, the @Override annotations instruct the compiler that the
annotated method is overriding the method.
2. Compile-time instructors:
It also provides compile-time instructions to the compiler that can be later used. The
programmers can use these as software build tools to generate XML files, code, etc.
3. Run-time instructions:
Defining annotations can also be helpful during runtime. We can access this using
Java Reflection.
Where can we implement Annotations in
Java?
We can implement annotations to classes, methods, fields, and interfaces in java.
Example:
@Override
void newMethod(){}
In this example, the annotation instructs the compiler that newMethod() is a method
that overrides. This method overrides (newMethod()) of its superclass.
Summary
This was all about annotations in java. Hope you enjoyed the article.

More Related Content

PPTX
Annotations
PPT
Understanding Annotations in Java
PPSX
Java annotations
PPTX
Java Annotations
PPTX
Annotations in Java Why are they important.pptx
PPTX
DOC-20240812-WA0000 array string and.pptx
PPTX
Module 4_CSE3146-Advanced Java Programming-Anno_Lambda-PPTs.pptx
PPTX
Java annotations
Annotations
Understanding Annotations in Java
Java annotations
Java Annotations
Annotations in Java Why are they important.pptx
DOC-20240812-WA0000 array string and.pptx
Module 4_CSE3146-Advanced Java Programming-Anno_Lambda-PPTs.pptx
Java annotations

Similar to Annotations in Java with Example.pdf (20)

PPTX
Java Annotations and Pre-processing
PPT
Annotations
PDF
Custom Annotations in Java with Project Lombok
ODP
Java Generics
KEY
About java
PPTX
introduction to object oriented programming language java
PPT
Java 5 Features
PPT
Java Annotation
PPTX
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
PDF
Class and Object JAVA PROGRAMMING LANG .pdf
PDF
Java 5 and 6 New Features
PPT
What is new in J2SE 5
PPTX
Class and Object.pptx from nit patna ece department
PDF
Java Programming - 04 object oriented in java
PPTX
JAVA-PPT'S-complete-chrome.pptx
PPTX
JAVA-PPT'S.pptx
PPTX
L03 Software Design
PPT
025466482929 -OOP with Java Development Kit.ppt
Java Annotations and Pre-processing
Annotations
Custom Annotations in Java with Project Lombok
Java Generics
About java
introduction to object oriented programming language java
Java 5 Features
Java Annotation
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
Class and Object JAVA PROGRAMMING LANG .pdf
Java 5 and 6 New Features
What is new in J2SE 5
Class and Object.pptx from nit patna ece department
Java Programming - 04 object oriented in java
JAVA-PPT'S-complete-chrome.pptx
JAVA-PPT'S.pptx
L03 Software Design
025466482929 -OOP with Java Development Kit.ppt
Ad

More from SudhanshiBakre1 (20)

PDF
IoT Security.pdf
PDF
Top Java Frameworks.pdf
PDF
Numpy ndarrays.pdf
PDF
Float Data Type in C.pdf
PDF
IoT Hardware – The Backbone of Smart Devices.pdf
PDF
Internet of Things – Contiki.pdf
PDF
Java abstract Keyword.pdf
PDF
Node.js with MySQL.pdf
PDF
Collections in Python - Where Data Finds Its Perfect Home.pdf
PDF
File Handling in Java.pdf
PDF
Types of AI you should know.pdf
PDF
Streams in Node .pdf
PDF
RESTful API in Node.pdf
PDF
Top Cryptocurrency Exchanges of 2023.pdf
PDF
Epic Python Face-Off -Methods vs.pdf
PDF
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
PDF
Benefits Of IoT Salesforce.pdf
PDF
Epic Python Face-Off -Methods vs. Functions.pdf
PDF
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
PDF
Semaphore in Java with Example.pdf
IoT Security.pdf
Top Java Frameworks.pdf
Numpy ndarrays.pdf
Float Data Type in C.pdf
IoT Hardware – The Backbone of Smart Devices.pdf
Internet of Things – Contiki.pdf
Java abstract Keyword.pdf
Node.js with MySQL.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdf
File Handling in Java.pdf
Types of AI you should know.pdf
Streams in Node .pdf
RESTful API in Node.pdf
Top Cryptocurrency Exchanges of 2023.pdf
Epic Python Face-Off -Methods vs.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Benefits Of IoT Salesforce.pdf
Epic Python Face-Off -Methods vs. Functions.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Semaphore in Java with Example.pdf
Ad

Recently uploaded (20)

PDF
Gestión Unificada de los Riegos Externos
PDF
Advancements in abstractive text summarization: a deep learning approach
PPTX
Build automations faster and more reliably with UiPath ScreenPlay
PPTX
Strategic Picks — Prioritising the Right Agentic Use Cases [2/6]
PDF
Connector Corner: Transform Unstructured Documents with Agentic Automation
PPT
Overviiew on Intellectual property right
PDF
substrate PowerPoint Presentation basic one
PDF
CCUS-as-the-Missing-Link-to-Net-Zero_AksCurious.pdf
PDF
Streamline Vulnerability Management From Minimal Images to SBOMs
PDF
NewMind AI Journal Monthly Chronicles - August 2025
PDF
ment.tech-Siri Delay Opens AI Startup Opportunity in 2025.pdf
PDF
Optimizing bioinformatics applications: a novel approach with human protein d...
PPTX
maintenance powerrpoint for adaprive and preventive
PPTX
Information-Technology-in-Human-Society (2).pptx
PDF
Examining Bias in AI Generated News Content.pdf
PPTX
AQUEEL MUSHTAQUE FAKIH COMPUTER CENTER .
PDF
Decision Optimization - From Theory to Practice
PPTX
Digital Convergence: How GIS, BIM, and CAD Revolutionize Asset Management
PDF
The AI Revolution in Customer Service - 2025
PDF
AI.gov: A Trojan Horse in the Age of Artificial Intelligence
Gestión Unificada de los Riegos Externos
Advancements in abstractive text summarization: a deep learning approach
Build automations faster and more reliably with UiPath ScreenPlay
Strategic Picks — Prioritising the Right Agentic Use Cases [2/6]
Connector Corner: Transform Unstructured Documents with Agentic Automation
Overviiew on Intellectual property right
substrate PowerPoint Presentation basic one
CCUS-as-the-Missing-Link-to-Net-Zero_AksCurious.pdf
Streamline Vulnerability Management From Minimal Images to SBOMs
NewMind AI Journal Monthly Chronicles - August 2025
ment.tech-Siri Delay Opens AI Startup Opportunity in 2025.pdf
Optimizing bioinformatics applications: a novel approach with human protein d...
maintenance powerrpoint for adaprive and preventive
Information-Technology-in-Human-Society (2).pptx
Examining Bias in AI Generated News Content.pdf
AQUEEL MUSHTAQUE FAKIH COMPUTER CENTER .
Decision Optimization - From Theory to Practice
Digital Convergence: How GIS, BIM, and CAD Revolutionize Asset Management
The AI Revolution in Customer Service - 2025
AI.gov: A Trojan Horse in the Age of Artificial Intelligence

Annotations in Java with Example.pdf

  • 1. Annotations in Java with Example In this article, we will learn about annotations in Java with syntax and examples. Annotations in Java The annotations represent the metadata i.e attached with the class, interface, function, or fields to denote a few additional information. The Java compiler and the JVM use this information during processing. Annotations in Java provide added information that can be used as an alternative option for XML and Java marker interfaces.These are not a part of the Java program, yet they provide access to add metadata information into the course code. Java introduced the concept of annotations from JDK5. As mentioned earlier, annotations provide only supplemental details about a program. It does not affect the operation of the code they annotate. More on java annotations: ■ They start with the symbol ‘@’. ■ Annotations do not modify the action or executions of a compiled program like its classes, variables, constructors, interfaces, methods, and many more. ■ We cannot consider them as mere comments. This is because annotations change the method a compiler treats a program. Built-in Java annotations:
  • 2. Before getting into custom or user-defined annotations, let us take a look at the built-in Java annotations. Some of the below-given annotations are applied to Java code and the rest are applied to other annotations. Built-in Java Annotations in Java code: ■ @Override ■ @SuppressWarnings ■ @Deprecated Built-in Java Annotations used in other annotations: ■ @Target ■ @Retention ■ @Inherited ■ @Documented Built-in Java Annotations Let us look at a brief description of the built-in annotations. 1. @Override: The @Override annotation makes sure that the subclass method overrides the parent class method. If this is not the case, it throws an error during compilation. It is easy to get rid of careless mistakes like spelling mistakes by marking the @Override annotation. It gives assurance that the method is overridden. Sample program to implement @Overrided annotation: class FirstCode{ void learnCourse(){ System.out.println("Learn Courses with FirstCode");
  • 3. }} class FirstCode2 extends FirstCode{ @Override void learnCourse(){ System.out.println("Learn Java with FirstCode"); }} class FirstCodeMain{ public static void main(String args[]){ FirstCode fc = new FirstCode2(); fc.learnCourse(); } } Output: Compile Time Error 2. @SuppressWarnings: This annotation suppresses the warning that the compiler issues. Sample program to implement @SuppressWarning annotation: import java.util.*; class FirstCode{ @SuppressWarning("unchecked") public static void main(String args[]){ ArrayList al = new ArrayList();
  • 4. al.add("Java"); al.add(C++); al.add("Python"); for(Object obj:al) System.out.println(obj); } } Output: Now no warning at compile time Once we remove the @SuppressWarning(“unchecked”) annotation, the compiler shows a warning due to the usage of non-generic collections. 3. @Deprecated: The @Deprecated annotation denotes that the particular method is deprecated, so the compiler prints the warning message. It also notifies the user that it may be eradicated in future versions. Therefore, it is good to avoid such methods. Sample program to implement @deprecated annotation: class FirstCode{ void course1(){ System.out.println("Learn Java with FirstCode"); } @Deprecated void course2(){
  • 5. System.out.println("Learn C++ with FirstCode"); }} class FirstCodeMain{ public static void main(String args[]){ Firstcode fc = new FirstCode(); fc.course2(); } } Output: During compilation:Note: Test.java uses or overrides a deprecated API. Note: Recompile with -Xlint:deprecation for details. During Runtime: Learn C++ with FirstCode 4. @Documented: It is a marker interface that informs a toll that an annotation is to be documented. As the annotations are not provided in the ‘Javadoc’ comments, the @Documented annotation takes care of it. It enables the tools like ‘Javadoc’ to include and process the annotation that is given in the document. 5. @Target: It is designed to use as an annotation to another annotation. @Target takes a parameter that is a constant from the ElementType enumeration. It denotes the type of declaration to which we can apply the annotation. The constants given in the below table are given with the type of the declaration to which it corresponds.
  • 6. Target Constant Annotations that can be applied to ANNOTATION_TYPE Another annotation CONSTRUCTOR Constructor FIELD Field LOCAL_VARIABLE Local variable METHOD Method PACKAGE Package PARAMETER Parameter TYPE Class, Interface, or enumeration There is flexibility to mention one or more of these values in a @Targetannotation. In such a case, we can mention them in the braces-delimited list. Eg: To denote an annotation that applies only to the local variables and fields, we can mention the @Target annotation as given below: @Target({Element.Type.FIELD, ElementType.LOCAL_VARIABLE}) 6. @Retention Annotation This denotes where and how long the annotation is retent. This annotation can hold three values:
  • 7. SOURCE: Annotations that are retained at the source level and ignored by the compiler. CLASS: Annotations that are retained at the source level and ignored by the JVM. RUNTIME: These annotations will be retained during the runtime. 7. @Inherited: The @Inherited annotation is a marker that is used to declare annotations. It has control over the annotations that are used in class declarations. @Inhertited causes the annotation for a superclass to be inherited by a subclass. Thus, when a request is made to the subclass and the annotation is absent in the superclass and annotated with @Inherited, then that annotation will be returned. @Inherited @interface FirstCode { } @interface FirstCode{ } class Superclass{} class Subclass extends Superclass{} Java User-defined annotation: User-defined annotations or custom annotations can annotate program elements. These elements include the variables, constructors, methods, etc. They are applied before the declaration of an element. Syntax: Declaration of a user-defined annotation: @interface NewAnnotation
  • 8. Here, NewAnnotation is the name of the annotation. Rules to declare user-defined annotation 1. AnnotationName is an interface. 2. The parameter should not be related to the method declarations and throw errors. 3. Null values cannot be assigned to these parameters. But they can have default values. 4. And these default values are optional. 5. The return type of the method must be either primitive, string, enum, an array of the primitive, class name, or class name type. Types of Annotation in Java: The annotations are classified into five main types: 1. Marker Annotation 2. Single-value Annotation 3. Full Annotation 4. Type Annotation 5. Repeating Annotation 1. Marker Annotation:
  • 9. This annotation is no method or any data. The only purpose of this annotation is to mark a declaration. As it has no members, simply determining if it is present or absent is enough. @Override and @Deprecated are examples for marker Annotation. Eg: @interface NewAnnotation{} 2. Single-value annotation: An annotation with just one method is known as a single-value annotation. It allows a shorthand form of assigning a value to a variable. All we need to do is, mention the value for the data member when we apply the annotation. We need not mention the name of the data member. But to use this shorthand, the name of the member should be a value. Snippet to implement single-value annotation: @interface NewAnnotation{ int value(); } Snippet to implement single-annotation with default value: @interface NewAnnotation{ int value() default 0; } Example to apply a single-value annotation: @NewAnnotation(value=5) 3. Full Annotation or Multi-value annotation:
  • 10. It is the annotation that consists of multiple values, data members, names, and pairs. Snippet to implement full annotation: @interface NewAnnotation{ int value1(); String value2(); String value3(); } } Example to implement full annotation with default values: @interface NewAnnotation{ int value1() default 1; String value2() default ""; String value3() default "FirstCode"; } Snippet to implement multi-value annotation: @NewAnnotation(value1=5, value2="FirstCode",value3="Java") 4. Type Annotation: We can apply this annotation where a type is present. For example, we can annotate the return type of a method. These are stated annotated with @Target annotation. Sample program to implement type annotation:
  • 11. import java.lang.annotation.ElementType; import java.lang.annotation.Target; @Target(ElementType.TYPE_USE) @interface TypeAnnoPgm{} public class FirstCode{ public static void main(String[] args) { @TypeAnnoPgm String string = "This string is annotated with a type annotation"; System.out.println(string); xyz(); } static @TypeAnnoPgm int xyz() { System.out.println("The return type of this function is annotated"); return 0; } } Output: This string is annotated with a type annotation The return type of this function is annotated 5. Repeating Annotations: As the name suggests, these annotations can be applied to the same item more than once. To make the annotation repeatable, we must annotate it with the @Repeatable annotation as defined in the java.lang.annotation package. The values in the field mention the contained type for the repeatable annotation. The contained
  • 12. is mentioned as an annotation whose value field is an array of the repeatable annotation type. To make an annotation repeatable, we must first create the container annotation. And we must mention the annotation type as an argument to the @Repeatable annotation. Sample program to implement repeating annotations: import java.lang.annotation.Annotation; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Method; @Retention(RetentionPolicy.RUNTIME) @Repeatable(MyRepeatedAnnos.class) @interface Words { String word() default "FirstCode"; int value() default 0; } @Retention(RetentionPolicy.RUNTIME) // Container annotation creation @interface MyRepeatedAnnos { Words[] value();
  • 13. } public class Main { @Words(word = "First Course = Java", value = 1) @Words(word = "Second Course = C++", value = 2) public static void newMethod() { Main obj = new Main(); try { Class c = obj.getClass(); Method m = c.getMethod("newMethod"); Annotation anno = m.getAnnotation(MyRepeatedAnnos.class); System.out.println(anno); } catch (NoSuchMethodException e) { System.out.println(e); } } public static void main(String[] args) { newMethod(); } } Output: @MyRepeatedAnnos(value={@Words(value=1, word=”First Course”), @Words(value=2, word=”Second Course”)})
  • 14. Building annotations in a real-world scenario: In reality, a Java programmer only needs to apply the annotation. It is not the task of the programmer to create or access annotations. These tasks are performed by the implementation provider. On behalf of the annotation, the Java compiler or the JVM performs various extra operations too. Sample program to implement User-defined annotations: package source; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Documented @Retention(RetentionPolicy.RUNTIME) @ interface MyAnnotation //user-defined annotations { String Developer() default "Programmer1"; String Expirydate(); } // will be retained at runtime public class FirstCode { @MyAnnotation(Developer="Programmer1", Expirydate="01-12-2023")
  • 15. void fun1() { System.out.println("Test method 1"); } @MyAnnotation(Developer="Progammer2", Expirydate="01-10-2024") void fun2() { System.out.println("Test method 2"); } public static void main(String args[]) { System.out.println("Learn Java with FirstCode"); } } Output: Learn Java with FirstCode Uses of Java Annotations: 1. Provides commands to the compiler: The built-in annotations help the programmers in giving various instructions to the compiler. For example, the @Override annotations instruct the compiler that the annotated method is overriding the method.
  • 16. 2. Compile-time instructors: It also provides compile-time instructions to the compiler that can be later used. The programmers can use these as software build tools to generate XML files, code, etc. 3. Run-time instructions: Defining annotations can also be helpful during runtime. We can access this using Java Reflection. Where can we implement Annotations in Java? We can implement annotations to classes, methods, fields, and interfaces in java. Example: @Override void newMethod(){} In this example, the annotation instructs the compiler that newMethod() is a method that overrides. This method overrides (newMethod()) of its superclass. Summary This was all about annotations in java. Hope you enjoyed the article.