Create your own annotation

Why to create annotation ?

  • For documentation purpose – Help the developers reading it understand
  • As an input to java source code processor

Libraries that use their own annotations ?

  • Spring & Spring Boot
  • Jackson JSON toolkit
  • Hibernate

Example of where annotations can be used :

Sample Annotation

Where annotation can be used

As displayed above it can be used for class, method, arguments,variables etc.

Providing values to annotation

  • Custome Annotation 2 elements
  • Class CustomeAnnotationExample1 uses the annotation and provides value to it
  • If not value is provided in below example, it will give compilation error since default value for that annotation is not provided

Providing default values to annotation

  • Now we don’t need to provide values to annotation anymore

Specifying where the annotation can be used

As you can see in the above screenshot

@Target annotation can be used to specify where CustomeAnnotation1 annotation can be sed

  • Used on Another annotation
  • Used on Constructor
  • Used on Local variable
  • Used on Method
  • Used on Package
  • Used on Parameter
  • Used on Type (Class)
  • Used on Type Parameter

Example :

The compiler gives warning that it cannot be used at that location because the @Target type for the annotation is TYPE i.e allowed only on classes

Example of using the value of Annotation in class

Output :

Reference :

Leave a Comment