Java Annotation Types

In Java, there are three types of annotations:

  1. Marker annotations
  2. Single-element annotations
  3. Multiple-element annotations

Let's take a closer look at each type.

  1. Marker Annotations:
    Marker annotations, as the name suggests, do not have any elements in them. They are used simply to mark the annotated element with some special meaning. An example of a marker annotation is the @Override annotation. This annotation is used to indicate that a method is meant to override a method from a parent class.

  2. Single-element Annotations:
    Single-element annotations have exactly one element in them. They are commonly used to provide a single piece of information that is associated with the annotated element. The most common example of a single-element annotation is @SuppressWarnings. This annotation is used to suppress compiler warnings.

Here is an example of a single-element annotation:

refer t‮gi:o‬iftidea.com
@SuppressWarnings("unchecked")
public void myMethod() {
  List myList = new ArrayList();
  // method body
}

In this example, the @SuppressWarnings annotation is used to suppress unchecked warnings. The value of the element is the string "unchecked".

  1. Multiple-element Annotations:
    Multiple-element annotations have more than one element in them. They are used to provide more complex information associated with the annotated element. An example of a multiple-element annotation is @RequestMapping. This annotation is used to map a method to a particular URL and HTTP method.

Here is an example of a multiple-element annotation:

@RequestMapping(value = "/my-url", method = RequestMethod.GET)
public void myMethod() {
  // method body
}

In this example, the @RequestMapping annotation is used to map the myMethod() method to the URL /my-url and HTTP method GET. The value element is the URL and the method element is the HTTP method.

You can also create your own custom annotations with any number of elements you need. To do this, you define an annotation type using the @interface keyword, and then specify the elements you want to include in the annotation.