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:
- The method should not have any throws clauses
- The method should return one of the following: primitive data types, String, Class, enum or array of these data types.
- The method should not have any parameters.
- We should attach @ just before the interface keyword to define annotation.
- 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(); } }
Comments
Post a Comment