Site icon codippa

How to create custom Annotation in java

A bit on Annotation

An annotation serves as meta data for a class. Annotation serves as compile time check for the compiler as well as run time instruction for execution environments.

Example:
Compile time: @Override annotation over a method informs the compiler that this method is overridden, hence should be present in the super class or implemented interface. If it is not, then error is raise.
Execution/Run time: @Autowired annotation over a field instructs the Spring container to inject a bean from its Application context into this field.

Creating an Annotation is a simple process

1. Create an interface with the name of your desired annotation as:

/* Target defines the elements on which this annotation may be applied such as a field, 
* method, class, constructor etc. If applied on an element other than the defined type a compiler 
* error will be raised*/
@Target(ElementType.METHOD)
/* Defines the visibility of this annotation. Possible values are 
*  SOURCE, CLASS and RUNTIME */
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation{
	String annotationVal();
} 

2. Define this annotation over a method using @ symbol as:

/* If there is a field in the annotation, then you need to provide a value to 
*  that field else this will be a compiler error */
@MyAnnotation(annotationVal="custom")
public void annotatedMethod(){
}

Let’s tweak in

  1. @Target and @Retention are themselves annotations.
  2. ElementType attribute of @Target annotation specifies the location at which created annotation may be applied. For example an annotation annotated with @Target(ElementType.FIELD) may ONLY be applied to instance variables.
  3. If no @Target is specified for an annotation then it may be applied anywhere.
  4. An annotation with RetentionPolicy other than RUNTIME is not visible at execution time.
  5. A default value may also be supplied for an annotation during its creation as:
    String annotationVal() default “custom”.
  6. If a default value is supplied, then there is no need to specify value while using annotation. Thus if a default value has been supplied, then we may also use annotation as:
    @MyAnnotation
    public void annotatedMethod(){}
    
Exit mobile version