Contents

Create an annotation and read its data

Writen by: David Vlijmincx

Introduction

Annotations are a form of metadata about a piece of Java code. This article will explain how to create an annotation that is available at runtime and how to access its data.

Creating an annotation

First, we create an annotation that we can use throughout this article. We will create an annotation that will store metadata about taxes. The tax annotation will have a name and value with a default of 21. The annotation needs to be annotated with @Retention(RetentionPolicy.RUNTIME) or we can't access it during runtime. This is the @Interface I will use:

1
2
3
4
5
@Retention(RetentionPolicy.RUNTIME)
public @interface Tax {
    String name();
    int value() default 21;
}

Using the annotation on a Class

Next, we need some classes to apply the annotation to. I have created two classes that inherit from car. We have a car class that uses an internal combustion engine(ICE) and an electric one. The ICE car will use the default value of 21, and we name this tax high emission. We call it low emission for the electric car and give it a lower tax value. The result looks like this.

1
2
3
4
5
6
7
class car{}

@Tax(name="high emission")
class IceCar extends car{}

@Tax(name="low emission", value = 16)
class ElectricCar extends car{}

Using annotation metadata

We start with creating an instance for each of the two car subclasses. On lines 5 and 10, we retrieve a reference to the tax metadata for IceCar and electricCar, respectively. You can get a reference to the annotation by calling getClass().getAnnotation(Tax.class) with the annotation's class on an instance. The object you got back has all the methods you need. For example, with carTax.name() we get the name of the tax that we declared on the class. In the example below, we access the metadata for both cars and print it to the console.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public void detectAndActOnAnnotation() {
    car iceCar = new IceCar();
    car electricCar = new ElectricCar();

    Tax carTax = iceCar.getClass().getAnnotation(Tax.class);
    if (carTax.value() > 20) {
    System.out.printf("This car uses the high tax bracket: %s%n", carTax.name());
    }

    Tax electricCarTax = electricCar.getClass().getAnnotation(Tax.class);
    System.out.printf("This car has %s With a value of %d%n", electricCarTax.name(), electricCarTax.value());

}

The console output is the following:

1
2
This car uses the high tax bracket: high emission
This car has low emission with a tax value of 16

Conclusion

In this article, we went over creating an annotation and applying it to a class. After we applied it, we used two car instances and retrieved the metadata from the tax annotation.

 




Questions, comments, concerns?

Have a question or comment about the content? Feel free to reach out!