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:
|
|
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.
|
|
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.
|
|
The console output is the following:
|
|
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.