Java Annotations Explained PDF
Java Annotations Explained PDF
You have 2 free stories left this month. Sign up and get an extra one for free.
“an·no·ta·tion | a-nə-ˈtā-shən
1: a note added by way of comment or explanation”
— Merriam-Webster
. . .
Anatomy of Annotations
The basic definition of an annotation type is simple:
1 @Retention(RetentionPolicy.RUNTIME)
2 @Target(ElementType.TYPE)
3 @Inherited
4 @Documented
5 public @interface MyAnnotation {
6 String name() default "";
7 int value();
8 }
Basic usage
The simplest annotation use would be @MyAnnotation at a compatible
target site.
@Retention
The typical lifecycle of our code is as follows:
Source Code
▼
▼ ◁ Compiler
▼
Class file
▼
▼ ◁ JVM
▼
Runtime
RetentionPolicy.SOURCE
RetentionPolicy.CLASS
RetentionPolicy.RUNTIME
@Target
Not every annotation makes sense on every available target. That’s why
we can explicitly set the acceptable targets. The eight available targets
are defined in java.lang.annotation.ElementType :
1 // Multi-Target
2 @Target({ ElementType.FIELD, ElementType.Type })
3
4 // Single-Target
5 @Target(ElementType.ANNOTATION_TYPE)
@Inherited
Annotations are not inherited by default. By adding @Inherited to an
annotation type, we allow it to be inherited. This only applies to
annotated type declarations, which will pass it down to their subtypes.
1 @MyAnnotation(value = 42)
2 public class MyType { ... }
3
4 // Any annotation check at runtime
5 // will also provide "MyAnnotation" and its value 42
6 public class MySubType extends MyType { ... }
@Documented
Java default behavior for documentation is to ignore any annotation.
With @Documented we can change this, making the metadata and its values
accessible through documentation.
@Repeatable
Until Java 8, we could apply a specific annotation type only once on a
target. With the help of the annotation @Repeatable , we can now declare
an annotation repeatable by providing an intermediate annotation:
1 @MyRepeatableAnnotation
2 @MyRepeatableAnnotation("Foo")
3 @MyRepeatableAnnotation("Bar")
4 public class MyType { ... }
. . .
Annotation Values
Being able to annotate our code and check if the annotation is present at
different lifecycle events is great. But providing additional values besides
the annotation type itself is even better. And even default values are
supported.
Primitive types
String
Enum types
Annotation types
Arrays are handled uniquely. If only a single value is provided when used,
we can omit the curly braces.
1 @Retention(RetentionPolicy.RUNTIME)
2 @Target(ElementType.TYPE)
3 public @interface Values {
4 String name() default "";
5 int value();
6 Class allowedTypes() default String.class,
7 ElementType[] types();
8 }
. . .
Built-In Annotations
The JDK includes multiple annotations beside the ones we already
encountered for creating annotation types itself:
@Override
@Deprecated
@FunctionalInterface
@SafeVarargs
@SuppressWarnings
. . .
Access metadata
Equivalent to boolean isAnnotationPresent(Class<? extends Annotation>
Classes
Methods
. . .
Use Cases
An excellent use-case is serialization. With annotations, a lot of
additional metadata can be provided on how our data structures should
be processed.
1 @Path("/1.0/login")
2 @Produces("application/json")
3 public class LoginResource {
4
5 @POST
6 @Path("/")
7 Response login(@FormParam("username") String username,
8 @FormParam("password") String passowrd,
9 @HeaderParam("User-Agent") String userAgent) {
10 ...
11 }
12
13 @HEAD
14 @Path("/")
15 Response ping() {
16 ...
17 }
18 }
This way, RestEASY can perform routing ( @Path ), validates allowed HTTP
methods ( @POST and @HEAD ), provides data extracted from the request
( @FormParam and @HeaderParam ), and uses a defined media type for the
response ( @Produces ).
All without any additional config file or objects. The configuration is right
there in the corresponding code.
. . .
Conclusion
Annotations are a great way to provide additional data, either for
ourselves or third-party tools and libraries. But be aware of the
additional costs of parsing, compiling, and lookup of annotations,
especially at runtime.
. . .
Resources
The Java Tutorials — Annotations (Oracle)
225 claps
WRIT T EN BY
Are Early Returns Any Simple Shell: What T he Chande Momentum Building an Image
Good? happens when you type Oscillator and In uxDB Downloader With
Daan in Better Programming ls -l? Anais Dotis in T he Startup Multiprocessing in
Emma Navarro in T he Startup Python
Amit Upreti in Better
Programming
Connecting graphical New to Ruby? Go Ahead How to Use Project Getting those pesky
objects to actions in and Pry! Lombok with Spring python modules to work
PyQt5 Dan Hutchinson Boot Isaac Adams
Wyatt Sharber, PhD Yiğitcan Nalcı in Javarevisited