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
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.
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
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
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,
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 .