Custom annotations in Java

 Java Custom annotations or Java User-defined annotations are easy to create and use. The @interface element is used to declare an annotation.

Example:

@interface SampleAnnotation{}  

Some key points:
  1. The method should not have any throws clauses
  2. The method should return one of the following: primitive data types, String, Class, enum or array of these data types.
  3. The method should not have any parameters.
  4. We should attach @ just before the interface keyword to define annotation.
  5. It may assign a default value to the method.

There are three types of annotations.

1. Marker Annotation: An annotation that has no method, is called marker annotation.

For example:

@interface SampleAnnotation{}  

The @Override and @Deprecated are marker annotations.

2. Single-Value Annotation: An annotation that has one method, is called a single-value annotation. 
For example:
@interface SampleAnnotation{  int value();  }  

How to apply Single-Value Annotation? Like below

@MyAnnotation(value=10)  

3.Multi-Value Annotation: An annotation that has more than one method, is called Multi-Value annotation. 
For example:
@interface SampleAnnotation{  int value1();  String value2();  String value3();  }  

How to apply Single-Value Annotation? Like below

@MyAnnotation(value1=10,value2="Arun Kumar",value3="Ghaziabad")  

Comments

Popular Posts

Linux commands 1 : Commonly used FILE AND DIRECTORY COMMANDS for daily use and interview

Most common used Docker Commands for SDETs

Running tests from maven command line: Different options