Understand the annotation

What are annotations

JAVA annotations, also known as JAVA annotations, are an Annotation mechanism introduced in JDK 1.5.

A more specific understanding is described as follows:

Annotations are tags that are inserted into the source code and can be manipulated using other tools.

JAVA Core Technology 2, 10th edition, P373

Further understanding of annotations

Note: this part of the content belongs to personal understanding, only for reference, there is a mistake welcome to leave a message to correct.

Look at the specific description, some baby may be more confused. Which begs the question, are annotations labels? How do I insert source code? What are the other tools? How do other tools handle annotations?

Before going any further into JAVA annotations, let’s take a quick look at how JAVA code is executed to make it easier to understand annotations.

  1. Java files (source code files)
  2. The Java compiler compiles source code files to generate bytecode files (class files)
  3. The JVM virtual machine executes instructions in bytecode files

From this process, we can learn that the code we write is source code, and the source code needs to be compiled into bytecode files before the JVM can execute the instructions in the bytecode files before the program is officially working.

And then four questions that might come to mind

1. Are annotations labels? 2. How to insert source code?

These two problems can not be over-interpreted, the role of annotation is a label to play the role of remarks and reminders, not active operation. Inserting code is simply putting annotations in a specific place in the code as modifiers like public.

3. What are the other tools?

As mentioned earlier, annotations are tags, so the corresponding question is who will handle these tags? We can give this handler a generic name, such as “annotation handler”. Since annotations can also be customized, the annotation handler cannot be completely built into the JAVA development kit. There will certainly be external import packages, such as the junit package needed to handle the “@test” annotation. Therefore, the “annotation handler” may be different depending on the annotation.

4. How do other tools handle annotations?

In the third question, we mentioned that we could generically define the tools for handling annotations as “annotation handlers.” These annotation processors handle annotations in two ways. The first way is at the source code level. The annotation processor can embed new code based on annotations before the source code file is compiled. One thing to note here is that you can’t modify an existing source file in this way, only create a new source file. The second way is to process class files in which the compiler has placed annotations. As mentioned earlier, the Java compiler compiles source code files to produce class files, and the JVM’s execution of class files can be considered program runtime, so the second approach can be considered characteristic of handling annotations while the program is running. In addition, dealing with annotations usually involves reflection.

Annotation syntax

Whether using annotations or custom annotations, understanding the basic syntax is essential.

Definition of the annotation interface (annotation type)

Annotation interface definition Demo
public @interface AnnotationName {
    String elementName1(a) default "defaultValue1";
    String elementName2(a) default "defaultValue2";
}
Copy the code
@interface

As shown in Demo, use @interface to create and define the annotation interface. Annotation is short for annotation interface declaration.

Pay attention to
  • All annotations interface implicitly extends the Java. Lang. The annotation. The annotation interface, and does not support extended again.
Annotation element
Element declaration format
type value(a) default value
Copy the code
Element type range
  • Basic data types (byte, short, int, float, double, Long, Boolean, char)
  • String
  • Class(Optional type parameter)
  • Enum type
  • Annotation type
  • Arrays of the above types (one-dimensional arrays only supported)
Pay attention to
  • The annotation element is required to be a compiler constant, so it cannot be set to NULL when passed in, and the default cannot be NULL.
  • You don’t have to set the default,

Annotation type declaration

Annotation type declaration syntax

The basic syntax Demo looks like this, @ annotation name (annotation element = annotation element value), can contain multiple annotation elements and values.

@ AnnotationName (elementName1 = "elementValue1", elementName2 = "elementValue2",...)
Copy the code
Tag annotation

If no annotation element is defined in the annotation interface, you can only declare the @annotation name when using the annotation. This type of annotation is called a markup annotation.

@AnnotationName
Copy the code
Single value annotation

If only one annotation element is defined in the annotation interface, then only the @annotation name (annotation element value) can be declared when using the annotation. This type of annotation is called a single-valued annotation. Note that the name of the annotation element in the annotation interface can only be “Value”.

@AnnotationName(elementValue)
Copy the code
Annotation type declaration scope

Annotations have a wide range of uses, and different annotations have their own scope of use. It can be divided into declarative annotations and type usage annotations according to the scope of use. The main scope of use is as follows

  • package
  • Classes (including enum classes)
  • Interfaces (including annotation interfaces)
  • methods
  • The constructor
  • Instance fields (including enum constants)
  • A local variable
  • Parameter variables (method parameters or constructor parameters)
  • Type parameters (including reference types)
Pay attention to the point
  • Use annotations on classes and interfaces before the class and interface keywords.
  • For variables, the annotation declaration is placed before the type.
  • For the type parameters of a generic class or method, the annotation declaration is placed between “<” and “>”, before the type parameters.
  • Usage conventions: State that annotations are placed before other modifiers, and type usage annotations are placed after other modifiers.
Note this

TODO to supplement

Standard annotations

Learn about annotations provided in java.lang, java.lang.annotation, and the Javax. Annotation package. It’s classified by range or use.

TODO to supplement

For details, see JAVA Core Technology 2 P386

Yuan notes

The meta-annotation scope applies only to the annotation interface and is used to describe the behavior properties of the annotation interface. There are four commonly used ones, namely @target, @Retention, @documented, and @Inherited

@Target

Describes the scope of the annotation interface.

The source code

The annotation interface contains only one annotation element, an array of type ElementType, which can be passed in as an anonymous array of ElementType values.

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
    /**
     * Returns an array of the kinds of elements an annotation type
     * can be applied to.
     * @return an array of the kinds of elements an annotation type
     * can be applied to
     */
    ElementType[] value();
}
Copy the code
ElementType

ElementType is an enum class, where enum constants represent scope.

Static constants meaning
TYPE Classes (including enum classes), interfaces (including annotation interfaces)
FIFLD Instance fields (including enum constants)
METHOD methods
PARAMTER Parameter or constructor parameter
CONSTRUCTOR The constructor
LOCAL_VARIABLE Member variables
ANNOTATION_TYPE Annotation type declaration
PACKAGE package
TYPE_PARAMTER Type parameter (JDK1.8)
TYPE_USE Type usage (JDK1.8)
MODULE Module declaration (JDK9)
Demo

The scope for AnnotationName, which represents the annotation interface, is the method and constructor.

@Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
public @interface AnnotationName {
    String element(a) default "defaultValue";
}
Copy the code
@Retention

Indicates the lifetime of the annotation interface.

The source code

As you can see from the source code, the Retention annotation interface has only one annotation element, a value of type RetentionPolicy. RetentionPolicy is an enum class where the enum constant represents the RetentionPolicy. The default RetentionPolicy is retentionpolicy.class.

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
    /**
     * Returns the retention policy.
     * @return the retention policy
     */
    RetentionPolicy value(a);
}
Copy the code
RetentionPolicy

RetentionPolicy is an enum class where the enum constant represents the RetentionPolicy.

Retention rules describe
SOURCE Annotations not included in the class file
CLASS Annotations are included in the class file, but the virtual machine does not need to load them
RUNTIME Annotations included in the class file and loaded by the virtual machine. They are available through the reflection API
Demo

AnnotationName, which represents an annotation interface, can exist in a class file, but the JVM does not retain the annotation when it works.

@Retention(RetentionPolicy.CLASS)
public @interface AnnotationName {
    String element(a) default "defaultValue";
}
Copy the code
@Documented

Prompt an archiving tool similar to Javadoc to archive the annotated interface.

@Inherited

Inheriting annotations. A subclass of the class annotated by the annotation interface inherits all the annotations of its parent class. So the annotation interface that uses Inherited annotations can only be used in the class domain.

Annotations for compilation

TODO to supplement

@Deprecated

This annotation can be used to annotate items that need to be repealed or not recommended (all the scope that annotations can be used).

@SuppressWarning

Tells the compiler to block specific types of warning messages.

@Override

Can only be used on a method, which is checked to see if it is from a superclass.

@Generated

Annotations used to manage resources

TODO to supplement

@PostConstruct
@PreDestory
@Resources
@Resource