DEV Community

Rajesh Mishra
Rajesh Mishra

Posted on

How To Create Custom Annotation In Java

Create Custom Annotation:

In java, creating an annotation is @interface is used to create an Annotation.

public @interface MyAnnotation{

}

We can also define methods inside an annotation.

public @interface MyAnnotation{
   int value();
}

Note: The methods of an annotation should adhere to the following rules:

  • Method declaration should not have any parameters
  • Method declaration should not have any throws clause
  • Method return type should be of primitives, String, Class, Enum, Annotations, and Arrays of the preceding types

Also, we can provide a default value for the methods inside an annotation.

public @interface MyAnnotation{
   int value() default 1;
}

Types of Annotations:

Top comments (0)