Annotations

This lesson discusses annotations in Java.

We'll cover the following...

Question # 1

What are annotations in Java and their utility?

Annotations, a form of metadata, provide data about a program that is not part of the program itself. Annotations can be easily recognized in code because the annotation name is prefaced with the @ character. Annotations have no direct effect on code operation, but at processing time, they can cause an annotation processor to generate files or provide informational messages. They are used for:

  • Annotations can be used by the compiler to detect errors or suppress warnings

  • Software tools can process annotation information to generate code, XML files, and so forth.

  • Some annotations are available to be examined at runtime and allow runtime processing.

Below is an example where a compiler is hinted to ignore warnings relating to unchecked generic operations using the annotation @SuppressWarnings. Annotations can be applied to declarations: declarations of classes, fields, methods, and other program elements.

Press + to interact
import java.util.List;
import java.util.ArrayList;
class Demonstration {
// uncommenting the below line remove the
// compile error
//@SuppressWarnings("unchecked")
public static void main( String args[] ) {
List companies = new ArrayList();
companies.add("Educative.io");
System.out.println(companies.get(0));
}
}

Question # 2

Give an example of creating a custom annotation

The annotation type definition looks similar ...