In this tutorial, you will learn about annotations, different Java annotations, and how to use them with examples.
Contents
What is annotation in Java, and how does it work?
Annotations in Java are used to provide metadata for your Java code. Because they are metadata, Java annotations do not directly affect the execution of your code, though some types of annotations can. Java annotations were introduced in Java 5 and are still in use today.
- Java annotations are metadata (data about data) for the source code of our program.
- They provide the compiler with additional information about the program but are not part of the program itself. These annotations have no effect on the compiled program’s execution.
Annotations begin with the letter @. Its syntax is as follows: @AnnotationName
Let’s look at the @Override annotation as an example:
The @Override annotation indicates that the method with this annotation overrides the method of the superclass with the same method name, return type, and parameter list.
When overriding a method, it is not required to use @Override. When we use it, however, the compiler throws an error if something goes wrong (for example, the wrong parameter type) while overriding the method.
Example: @Override Annotation Example
class Sample { public void displayInfo() { System.out.println("I am an Sample class."); } } class Demo extends Sample { @Override public void displayInfo() { System.out.println("I am a demo class."); } } class Main { public static void main(String[] args) { Demo d = new Demo(); d.displayInfo(); } }
Output
I am a demo class.
The method displayInfo() is present in both the superclass Sample and the subclass Demo in this example. When this method is invoked, the method of the subclass is invoked rather than the method of the superclass.
Types of Annotations
Predefined annotations | Meta-annotations |
---|---|
@Deprecated @Override @SuppressWarnings @SafeVarargs @FunctionalInterface | @Retention @Documented @Target @Inherited @Repeatable |
Use of Annotations
In Java, there are several built-in annotations. Some annotations are used on Java code, while others are used on other annotations.
- Compiler instructions– Annotations can be used to give the compiler instructions, detect errors, and suppress warnings. For these purposes, the built-in annotations @Deprecated, @Override, and @SuppressWarnings are used.
- Compile-time instructions – These annotations provide compile-time instructions that help software build tools generate code, XML files, and more.
- Runtime instructions – Annotations can be used to give the program instructions at runtime. Java Reflection is used to access these annotations.
Annotation formats
Elements like (members/attributes/parameters) may also be included in annotations.
Marker Annotations
Marker annotations are Java annotations that do not have any members or data. Because marker interfaces do not have any members, simply declaring the annotation in your code is enough to influence the output in whatever way you want.
Members/elements are not present in marker annotations. It is only used to indicate a declaration.
Syntax:
@AnnotationName()
Parentheses can be omitted because these annotations do not contain elements. As an example:
@Override
Single element Annotations
There is only one element in a single element annotation.
Syntax:
@AnnotationName(elementName = “elementValue”)
- If there is only one element, it is customary to refer to it as value.
@AnnotationName(value = “elementValue”)
The element name can also be excluded in this case. By default, the element name will be value.
@AnnotationName(“elementValue”)
Multiple element Annotations
Multiple elements are separated by commas in these annotations.
Syntax:
@AnnotationName(element1 = “value1”, element2 = “value2”)
Annotation placement
An annotation can be added to any declaration by placing it on top of it. Annotations can now be placed before a type in Java 8.
Above declarations
As previously stated, Java annotations can be placed above declarations of classes, methods, interfaces, fields, and other program elements.
Example: @SuppressWarnings Annotation Example
class Main { @SuppressWarnings("unchecked") static void wordsList() { ArrayList word = new ArrayList<>(); // This causes an unchecked warning word.add("DevelopersDome"); System.out.println("Word: " + word); } public static void main(String args[]) { words(); } }
Output:
Word: [DevelopersDome]
If the above program is not compiled with the @SuppressWarnings(“unchecked”) annotation, the compiler will still compile it but will issue warnings such as:
Main.java uses unchecked or unsafe operations.
Word: [DevelopersDome]
We’ve received the warning.
Main.java uses unchecked or unsafe operations.
Because of the following statement:
ArrayList word = new ArrayList<>();
This is because the array list’s generic type hasn’t been defined. This warning can be avoided by using generics inside angle brackets <>.
ArrayList word = new ArrayList<>();
Type annotations
Prior to Java 8, annotations could only be used on declarations. Type annotations are now available as well. This means that we can use annotations anywhere a type is used.
Constructor invocations
new @Readonly ArrayList<>()
Type definitions
@NonNull String str;
To avoid a NullPointerException, this declaration specifies the non-null variable str of type String.
@NonNull List newList;
This declaration specifies a String list that is not null.
List<@NonNull String> newList;
This declaration specifies a list of String non-null values.
Built-in Annotations used in custom annotations
- @Target
- @Retention
- @Inherited
- @Documented
@Target
The @Target tag is used to specify which type the annotation should be applied to.
The ElementType enum contains a number of constants that specify the type of element to which annotation should be applied, such as TYPE, METHOD, FIELD, and so on. Let’s look at the ElementType enum’s constants:
Element Types | Where can the annotation be used? |
---|---|
TYPE | class, interface, or enumeration |
FIELD | fields |
METHOD | methods |
CONSTRUCTOR | constructors |
ANNOTATION_TYPE | annotation type |
Example to specify annoation for a class
@Target(ElementType.TYPE)
@interface MyAnnotation{
int valueA();
String valueB();
}
Annotation for a class, methods, or field is an example
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
@interface MyAnnotation{
int valueA();
String valueB();
}
@Retention
The @Retention annotation specifies the level of annotation that will be available.
RetentionPolicy | About |
---|---|
RetentionPolicy.SOURCE | refers to the source code that was thrown away during the compilation process. It will be absent from the compiled class. |
RetentionPolicy.CLASS | refers to the.class file, which is accessible by the Java compiler but not by the JVM. It is part of the class file. |
RetentionPolicy.RUNTIME | refers to the runtime that the Java compiler and JVM have access to. |
Example to specify the RetentionPolicy
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface MyAnnotation{
int valueA();
String valueB();
}
@Inherited
Annotations are not passed down to subclasses by default. The @Inherited annotation specifies that the annotation should be passed down to subclasses.
@Inherited
@interface ForEveryone { }
@interface ForEveryone { }
class Superclass{}
class Subclass extends Superclass{}
@Documented
The annotation is marked as @Documented and will be included in the documentation.
It’s a marker interface that instructs a tool to document an annotation. ‘Javadoc’ comments do not include annotations. When you use the @Documented annotation in your code, it allows tools like Javadoc to process it and include information about the annotation type in the generated document.
java annotations, java custom annotation, java override annotation, how to create custom annotation in java,use of annotations in java,java annotations, java custom annotation, java override annotation, how to create custom annotation in java,use of annotations in java,java annotations, java custom annotation, java override annotation, how to create custom annotation in java,use of annotations in java,java annotations, java custom annotation, java override annotation, how to create custom annotation in java,use of annotations in java,java annotations, java custom annotation, java override annotation, how to create custom annotation in java,use of annotations in java,java annotations, java custom annotation, java override annotation, how to create custom annotation in java,use of annotations in java
You may like:
Try-with-resources in java with Example
Java enum Constructor with Example
Java Inheritance with Example | Types of inheritance
Java final Keyword with Example
Java Polymorphism with Example
Singleton Class in Java with Implementation and Example
Java Nested and Inner Class with Example
Hope this article will guide you to recognize all about Java Annotations with Examples that you needed and still if you have any problem or queries regarding this, post them in the comments section and we will be glad to assist you.