English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, we will learn what annotations are, different Java annotations, and how to use them through examples.
Java annotations are the metadata of our program source code (data about data).
They provide additional information about the program to the compiler, but are not part of the program itself. These annotations do not affect the execution of the compiled program.
Annotations start with @. Their syntax is:
@AnnotationName
Let's take the @Override annotation as an example.
@Override annotation specifies that the method annotated with it overrides the method with the same name, return type, and parameter list of the superclass.
When rewriting methods, it is not necessary to use @Override. However, if we use it, the compiler will give an error if there is an error in the method override (such as incorrect parameter type).
class Animal { public void displayInfo() { System.out.println("I am an animal."); } } class Dog extends Animal { @Override public void displayInfo() { System.out.println("I am a dog."); } } class Main { public static void main(String[] args) { Dog d1 = new Dog(); d1.displayInfo(); } }
Output result
I am a dog.
In this example, the method displayInfo() exists in both the superclass Animal and the subclass Dog. When calling this method, the method of the subclass will be called instead of the method in the superclass.
Annotations can also include elements (members/Properties/Parameters).
Marker annotations do not contain members/Elements. It is only used to mark declarations.
The syntax is:
@AnnotationName()
Since these annotations do not contain elements, parentheses are not required. For example,
@Override
Single-element annotations only contain one element.
The syntax is:
@AnnotationName(elementName = "elementValue")
If there is only one element, it is customary to name the element value.
@AnnotationName(value = "elementValue")
In this case, the element name can also be removed. The default element name value is used.
@AnnotationName("elementValue")
These annotations contain multiple elements separated by commas.
The syntax is:
@AnnotationName(element1 = "value1", element2 = "value2")
Any declaration can be annotated by placing it above the declaration. From Java 8Starting with Java 5, comments can also be placed before the type.
As described above, Java comments can be placed above the declarations of classes, methods, interfaces, fields, and other program elements.
import java.util.*; class Main { @SuppressWarnings("unchecked") static void wordsList() { ArrayList wordList = new ArrayList<>(); //This will result in unchecked warnings wordList.add("w")3codebox"); System.out.println("Word list => " + wordList); } public static void main(String args[]) { wordsList(); } }
Output result
Word list => [w3codebox]
If the above program is compiled without the @SuppressWarnings("unchecked") annotation, the compiler will still compile the program, but will give the following warning:
Main.java uses unchecked or unsafe operations. Word list => [w3codebox]
We receive a warning
Main.java uses unchecked or unsafe operations
Because of the following statement.
ArrayList wordList = new ArrayList<>();
This is because we have not defined the generic type for ArrayList. We can resolve this warning by specifying generics within the angle brackets <>.
ArrayList<String> wordList = new ArrayList<>();
In Java 8Previously, comments could only be applied to declarations. Now, type annotations can also be used. This means we can place annotations anywhere types are used.
Constructor call
new @Readonly ArrayList<>()
Type definition
@NonNull String str;
This declaration specifies a non-null variable str of type String to avoid NullPointerException.
@NonNull List<String> newList;
This declaration specifies a non-null list of String types.
List<@NonNull String> newList;
This declaration specifies a list of non-null String values.
Type conversionnewStr = (@NonNull String) str;
extends and implements clauses
class Warning extends @Localized Message
throws Clause
public String readMethod() throws @Localized IOException
Type annotations make Java code more analyzable and provide stronger type checking.
1. Predefined Annotations
@Deprecated
@Override
@SuppressWarnings
@SafeVarargs
@FunctionalInterface
2. Meta Annotations
@Retention
@Documented
@Target
@Inherited
@Repeatable
3. Custom Annotations
These annotation types are inJava Annotation TypesDetailed descriptions are provided in the tutorial.
Compiler Instructions - They can be used to provide instructions to the compiler, detect errors, or suppress warnings. Such as built-in annotations @Deprecated, @Override, @SuppressWarnings.
Compile-time Instructions - These comments provide compile-time instructions that help software build tools generate code, XML files, etc.
Runtime Instructions - Some annotations can be defined to provide instructions to the program at runtime. These annotations are accessed using Java reflection.