Java — Annotations

Ben Parker
2 min readJan 9, 2021

--

Annotations and the Reflection API are used together.

Annotations do not alter the code in any way, they stand to add extra information in the form of meta-data. This meta-data is only useful is some application is actively searching for it. This is where the Reflection API is useful.

You create new annotations in the same way as you define new interfaces.

public @interface <AnnotationName>

Annotations take two annotations as meta-data. This tells the Javac compiler where your annotation will be made available. These options are:

  • Target( ElementType — Type, Method, Field etc )
  • Retention ( RetentionPolicy — RUNTIME, SOURCE or CLASS )

These tell the compiler what components your annotation can be used on ( target ) and how long your annotation will be retained ( compile time only, or all the way through to runtime )

Reflection API

The reflection api allows you to then access the annotations from the class as you have direct access to the class file after compile time. You are able to scan the class and look for annotations at each level, class, field and method.

This feature is useful, as you can then implement whatever logic you want if the annotation is found. You could invoke certain methods or custom logic. This could modify code or alter variable state.

In order to do this you can make use of the method :

getAnnotations() or getAnnotationsByType()

If you combine these 2 tools, you’re able to build more complex projects such as Frameworks ( Spring, JUnit ). Your IDE will depend heavily on annotations as well, for things such as “Override” and “Deprecated”.

For more information about the Reflection API — See here

--

--