How to create custom annotation in java : Step by step explanation

Before discussing  how to create a custom annotation in java , we have already shared  java annotations tutorials for beginners  . Sometimes in our web services we need to create custom annotation . So let us understand the term annotation first before discussing custom annotation . Annotation is a kind of meta data , in other words ,it represents data about data .

The great myth behind why @ symbol was chosen for annotations.
@: AT: Annotation Type


Read Also :      Java Annotation tutorials for beginners

                         Top 10 most frequently used Annotation  Examples
    

 
how to create custom annotation in java with example



Java annotation can be useful to provide property of class or object .There are 3 steps involved in creating custom annotation .Below are the steps  to create custom annotation in java along with example.








Step 1 

Create an annotation with the following code in MySampleAnnotation.java


package com.sample.annotation;

public @interface MySampleAnnotation //@ symbolizing that this is an Annotation
                                       Type
{ 
    public String name();   // The scope here matches with the conventions
                               followed for an interface. Default is public
                               and that’s the only allowed modifier
    public int age();       // The scope here matches with the conventions
                               followed for an interface. Default is public
                               and that’s the only allowed modifier   
}


The annotation type has all the features equal to that of an interface, exceptions are
1) Specifying @ symbol before interface keyword
2) Allowing of default values to its method


Step 2

Create a client class that uses the above created annotation, as below,



package com.sample.annotation;

public class MySampleAnnotationClient {
    public static void main(String args[]) {
        MySampleAnnotationClient mySampleAnnotationClient =                    
                                      new   MySampleAnnotationClient(); 
        mySampleAnnotationClient.myMethod();  
    }
    
    @MySampleAnnotation(name = "Sreenivasan Arumugam", age = 29) 
 
      //We give the values to the attributes
        of an annotation as a comma-separated values
 
 public void myMethod() {
        System.out.println("Alive is awesome");
    }
}



Step 3

Compile and execute the above program, you should get the output as below,

      

Alive is awesome

Cheers !!! you have created your first annotation .

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry