How To Create Custom Annotations In Java

17 Flares Twitter 0 Facebook 0 Google+ 13 LinkedIn 4 Filament.io 17 Flares ×

This tutorial is about creating custom annotations in Java. Ever since Java started supporting annotations, most of the frameworks embraced annotations and now annotations are the best way to define the extra services that a class requires. Much cleaner and easier than XML or properties file based alternatives. Annotations do not directly affect program semantics, but they do affect the way programs are treated by tools and libraries. Hence Annotations are a way to tell what all services a class needs or how it needs to be treated by the run time framework. To create an annotation we need to define an interface. It is a normal interface but with an @ infront. ( @interface). The @interface declarations informs java that this is custom annotation.

 

Annotation Definition

@Target(ElementType.METHOD)  – this annotation is only meant to be applied for methods.

boolean active() – Method declarations must not have any parameters or a throws clause.

Class with @Hello Annotation

 Processing the Annotation

Output

Running methodA

 

 What has Happened

Created a custom annotation named Hello , applied the annotation to HelloWorld class, Written an AnnotationProcessor ( mimicking framework classes) that processes the annotation.

 

  • amit

    if I used @Hello in differnet class like HelloWorld1, HelloWorld2 ……then I have to process all classes in AnnotationProcessor . This looks very odd to me. Even How can AnnotationProcessor know in which classes @Hello annotaion is going to be used. I am not clear with the annotation internal working.Please explain