Introduction
In this article, we discuss custom annotation in Java.
What is Custom Annotation?
Custom Annotation creation is similar to writing an interface, but it differs in the implementation since it uses a prefix, the "@" symbol. We can declare methods in annotations. We can create the user-defined annotation also. The @interface elements is used to declare an annotation.
Syntax
@interface OurAnnotation{}
Some points to remember
Programmers must remember some points about annotations; they are:
- Methods don't contain parameters.
- Methods don't contain any throws clauses.
- Methods must return one of the following: primitive data types, a Class, String, enum or array.
- We should prefix @ just before the interface keyword to define an annotation.
- It may assign a default value to the method.
Types of Annotations
There are basically three types of annotations, they are:
- Single-Value
- Multi-Value
- Marker Annotation
1. Marker Annotation
When no methods are used in an annotation, it is called a marker annotation. For example:
@interface OurAnnotation{}
2. Single-Value Annotation
As the name indicates, it contains only one method. For example:
- @interface OurAnnotation {
- int val() default ();
- }
- We can provide the
- default value also.For example: @interface OurAnnotation {
- int val() default 0;
- }
How to apply a Single-Value Annotation?
Let's see the following code to apply the single value annotation.
@OurAnnotation (val=20)
The value can be anything.
3. Multi-Value Annotation
According to its name, the annotation that has more than one method is called Multi-Value annotation. For example:
- @interface OurAnnotation {
- int val1();
- String val2();
- String val3();
- }
- }
We can provide the default value also. For example:
@interface OurAnnotation
- {
- int val1() default 1;
- String val2() default "";
- String val3() default "abc";
- }
How to apply Multi-Value Annotation?
Let's see the following code to apply a multi-value annotation.
@OurAnnotation (val1=20, val2="Jaun Pol", val3="Noida")
Built-In-Annotation
Built-In-Annotations applied to other annotations (Custom annotations) are:
- @Inherited
- @Documented
- @Target
- @retention
@Target
This tag specifies which type is to be used.
The "java.lang.annotation.ElementType" enum declares many constants to specify the type of element for annotation, such as TYPE, METHOD, FIELD, etcetera. Let's see the constants of the ElementType enum.
| Element Types | Where the annotation can be applied |
| TYPE | class, interface or enumeration |
| FIELD | fields |
| METHOD | methods |
| CONSTRUCTOR | constructors |
| LOCAL_VARIABLE | local variables |
| ANNOTATION_TYPE | annotation type |
| PARAMETER | parameter |


Join the conversation! Your thoughts help the community grow.