Thursday, August 15, 2019

Java Annotation 101

JDK 5.0 introduced a few new features including Generics, For/in loop, Autoboxing/Unboxing, Typesafe Enums, Varargs, Static Import and Annotation. This is about 15 years ago, but it is still valuable to do a quick review of this release, esp. the annotation.

Annotations are like meta-tags that you can add to your code and apply to package declarations, type declarations, constructors, methods, fields, parameters and variables.

Simply speaking, an annotation is a mechanism for associating a meta-tag with program elements and allowing the compiler or the VM to extract program behaviors from these annotated elements and generate interdependent code when necessary.

Usually you need use @interface to define an annotation type, then annotate your codes using @MyAnnotation.

There are three annotation types:
  • Marker type annotation has no elements, except the annotation name itself.
  • Single-element, or single-value type, annotation provides a single piece of data only. This can be represented with a data=value pair or, simply with the value (a shortcut syntax) only, within parenthesis.
  • Full-value type annotation has multiple data members. Therefore, you must use a full data=value parameter syntax for each member.
There are two types of annotations available with JDK5:
  • Simple
  • Meta
There are only three types of simple annotations provided by JDK5. They are:
  • Override
  • Deprecated
  • SuppressWarnings
Meta-annotations, which are actually known as the annotations of annotations, contain four types.
  • Target
  • Retention
  • Documented
  • Inherited

No comments:

Post a Comment