In Java, annotations and annotation processors are surrounded by a shroud of mystery for most. They seem like a subject reserved for "experts". On top of that, I believe there’s also some FUD around them. This post aims to dig into the subject, in the most neutral way possible. This way, everybody can take enlightened decisions based on facts, not by listening to people full of misconceptions or hidden agendas. Annotations are available since Java version 5, codenamed , and released in 2004. Tiger In the Java computer programming language, an annotation is a form of syntactic metadata that can be added to Java source code. Classes, methods, variables, parameters and Java packages may be annotated. — Wikipedia https://en.wikipedia.org/wiki/Java_annotation The most simple annotation looks like the following: {} @MyAnnotation public class Foo Because of the lack of annotations, previous Java versions had to approach some features in oblique ways. Replacement of marker interfaces Since Java’s inception, there has been a need to mark a class, or a hierarchy of classes. Before Java 5, this has been done through . and are two examples of such interfaces. interfaces with no methods Serializable Cloneable This kind of interface obviously is unlike any other: they don’t define any contract between themselves and their implementing classes. Hence, they have earned the name of marker interfaces. People new to Java will in general ask questions related to that approach. The reason for that is because it’s a trick. Annotations remove the need for that trick, and keep the contract role of interfaces. {} {} public class Foo implements MarkerInterface // 1 @MyAnnotation public class Foo // 2 Marker interface Annotation equivalent to the marker interface Better metadata management Deprecation is the process of flagging an API as obsolete. This way, users are informed about the change, can decide to stop using the API, and the latter may be removed with less impact in future versions. Prior to Java 5, deprecation was set in the JavaDocs: {} /** * Blah blah JavaDoc. * * As of JDK version 1.1, */ @deprecated public class DeprecatedApi Obviously, this is a very fragile approach: the only way to leverage it is via the tool. The standard JavaDocs has a . Alternatively, the tool can be configured via a custom , to process Javadoc metadata (including but not limited to ) in any desired way. javadoc section dedicated to such deprecated APIs javadoc doclet @deprecated Java 5, deprecation is flagged with the provided annotation: @Deprecated {} /** * Blah blah JavaDoc. */ @Deprecated public class DeprecatedApi NOTE: Old deprecated APIs keep the old approach, so they use both metadata and annotation. Additionally, since Java 9, allows two elements: @Deprecated (of type ): indicates whether the annotated element is subject to removal in a future version forRemoval boolean (of type String): returns the version in which the annotated element became deprecated since (since= , forRemoval= ) {} @Deprecated "1.2" true public abstract class IdentityScope extends Identity Creating an annotation To create an annotation, one uses the keyword: @interface MyAnnotation {} public @interface However, this is not enough, as such an annotation cannot be set anywhere. Annotations require two more pieces of information: A : this defines where the annotation can be set target A : this describes up to which step in the compilation process the annotation will be available retention We will get into more detail later. As for now, we first need to understand how annotations work. While classes inherit code from their parent class(es), . annotations are composed (ElementType.ANNOTATION_TYPE) Foo {} (ElementType.ANNOTATION_TYPE) Bar {} Baz {} @Target // 1 @interface @Target // 1 @interface @Foo @Bar @interface // 2 This is the required , it will be explained further down @Target Something annotated with is transitively annotated with both and @Baz @Foo @Bar Here’s the source code of and : @Target @Retention (RetentionPolicy.RUNTIME) (ElementType.ANNOTATION_TYPE) Target { ElementType[] value(); } (RetentionPolicy.RUNTIME) (ElementType.ANNOTATION_TYPE) Retention { ; } @Retention // 2 @Target // 1 public @interface @Retention // 2 @Target // 1 public @interface RetentionPolicy value () The annotations tells on which element the annotation can be set: @Target On a type a class or an interface e.g. On another annotation On a field On a method On a constructor On a method parameterOn a local variableOn a moduleetc. The annotation defines up to which step in the compilation process the annotation will be available: @Retention Only the source code In the class file At runtime This is summed up in the following class diagram: Annotation parameters Annotations can define . Parameters allow to add some level of configuration at the time the annotation is used. A parameter accepts a and an optional . If the value is not set when the annotation is defined, it needs to be when it is used. parameters type default value Parameter types are limited to the following: Any primitive type , , etc. e.g. int long String Class<T> Any type enum Another annotation type Any array of the above (ElementType.CLASS) Foo { ; Class<? extends Collection> baz() List.class; String[] qux(); } (bar = , qux = { , , }) {} @Target @interface int bar () default @Foo 1 "a" "b" "c" class MyClass If there’s a and it’s named value, its name can be omitted when set: single parameter (ElementType.CLASS) Foo { ; } ( ) {} @Target @interface int value () @Foo 1 class MyClass Handling annotations at runtime: reflection Since its inception, Java has allowed : reflection is the capacity to get information about the code at runtime. Here’s a sample: reflection session = request.getHttpSession(); object = session.getAttribute( ); clazz = object.getClass(); methods = clazz.getMethods(); ( method : methods) { (method.getParameterCount() == ) { method.invoke(foo); } } var var "objet" // 1 var // 2 var // 3 for var if 0 // 4 // 5 Get an object stored in the session Get the runtime class of the object Get all methods available on the object public If the method has no parameter Call the method With annotations, the reflection API got relevant improvements: With annotation, frameworks started to make use of them for different use-cases. Among them, configuration was one of the most used: for example, instead of (or more precisely in addition to) XML, the added a configuration option based on annotations. Spring framework Handling annotations at compile-time: annotation processors For a long time, both users and providers were happy with runtime reflection access to annotations. Because it’s mainly focused on configuration, reflection occurs at startup time. In constrained environments, this is too much of a load for applications: the most well-known example of such an environment is the Android platform. One would want to have the fastest startup time there, and the startup-time reflection approach makes that slower. An alternative to cope with that issue is to . For that to happen, the compiler must be configured to use specific . Those can have different outputs: simple files, generated code, etc. The tradeoff of that approach is that compilation takes a performance hit time, but then startup time is not impacted. process annotations at compile-time annotation processors every One of the earliest frameworks that used this approach to generate code was : it’s a Dependency-Injection framework for Android. Instead of being runtime-based, it’s compile-time based. For a long time, compile-time code generation was limited to the Android ecosystem. Dagger However, recently, back-end frameworks such as and also adopted this approach. The aim is to reduce application startup time through compile-time code generation in replacement of runtime introspection. Additionally, Ahead-of-Time compilation of the resulting to native code further reduces startup time, as well as memory consumption. Quarkus Micronaut bytecode The world of annotation processors is huge: this section is a but a very small introduction so one can proceed further if wanted. A processor is just a specific class that needs to be registered at compile-time. There are several ways to register them. With Maven, it’s just a matter of configuring the compiler plugin: org.apache.maven.plugins maven-compiler-plugin 3.8.1 ch.frankel.blog.SampleProcessor < > build < > plugins < > plugin < > groupId </ > groupId < > artifactId </ > artifactId < > version </ > version < > configuration < > annotationProcessors < > annotationProcessor </ > annotationProcessor </ > annotationProcessors </ > configuration </ > plugin </ > plugins </ > build The processor itself needs to implement , but the abstract class implements most of its methods but process: in practice, it’s enough to inherit from . Here’s a very simplified diagram of the API: Processor AbstractProcessor AbstractProcessor Let’s create a very simple processor. It should only lists classes that are annotated with specific annotations. Real-world annotation processors would probably do something useful generate code, but this additional logic goes well beyond the scope of this post. e.g. ( ) (SourceVersion.RELEASE_8) { { annotations.forEach(annotation -> { Set<? extends Element> elements = env.getElementsAnnotatedWith(annotation); elements.stream() .filter(TypeElement.class::isInstance) .map(TypeElement.class::cast) .map(TypeElement::getQualifiedName) .map(name -> + name + + annotation.getQualifiedName()) .forEach(System.out::println); }); ; } } @SupportedAnnotationTypes "ch.frankel.blog.*" // 1 @SupportedSourceVersion public class SampleProcessor extends AbstractProcessor @Override public boolean process (Set<? extends TypeElement> annotations,// RoundEnvironment env) 2 // 3 // 4 // 5 // 6 // 7 "Class " " is annotated with " return true will be called for every annotation that belongs to the package Processor ch.frankel.blog is the main method to override process() The loop will be called for each annotation The annotation is not as interesting as the element annotated with it. This is the way to get the annotated element. Depending on which element is annotated, it needs to be cast to the correct subinterface. Here, only classes can be annotated, hence, the variable needs to be tested to check whether it’s assignable to access its additional attributes further down the operation chain Element TypeElement We want the qualified name of the class the annotation is set on, so it’s necessary to cast it to the type that makes this specific attribute accessible Get the qualified name from TypeElement Conclusion Annotations are very powerful, whether used at runtime or at compile-time. On the flip side, the biggest issue is that they seem to work like magic: there’s no easy way to know which reflection-using class or annotation processor is making use of them. It’s up to everyone in one’s own context to decide whether their pros out-weight their cons. To use them without any forethinking does a great disservice to one’s code… a disservice just as great as discarding them because of misplaced ideology. I hope this post shed some light on how annotations work, so one can decide for oneself. The complete source code for this post can be found on in Maven format. Github To go further: Marker Interfaces in Java Doclet Overview Java Language Specifications: Annotation Types Java Language Specifications: Annotations Trail: The Reflection API Java Annotation Processing and Creating a Builder First published on April 26th 2020 on A Java Geek