Java is not a language with training wheels. It is a language for professional programmers.

— Hebert Sheildt

Create Your Own Annotation

Annotations are the nothing but meta-data, i.e. it provides information about the code. Annotations are widely used for configuration purpose like in the Hibernate, Spring framework, etc. You must have come across the annotation like @Override, @Deprecated, @Author, etc. Here we’ll create our own annotation.

Creating an annotation is certainly very easy. The syntax is :

We will create a very simple annotation which will provide information for calculating.

We will be using @Retention(RetentionPolicy.RUNTIME) as we want our created annotation to be queried at runtime by any java program. If this is not used, we will not be able to query our annotation during runtime using reflection.

The annotation will have three attributes, number1, number2 and operation.In the operation attribute we will specify the mathematical operation that we want to perform, our annotation allows only addition and subtraction operation.

Default values for the attributes can be specified using default keyword followed by the value.

Here’s the class, in which we will be using our created annotation

Now that we have information provided by the annotation, we further need to process the information as required.

Both the methods are called by, we first invoke the method by using reflection, then we process the annotation by performing the mathematical operation based on the if condition and print it on the console.

Kindly take a note of the System.out.print/ln() in both the java files to understand the flow better.

© Copyright © 2013 All Rights Reserved.