java annotations (Annotation) implementation principle

First, the introduction of notes

Notes is a java-language feature, introduced at the beginning of java5 when located java.lang.annotation package.

Concept: annotation for additional metadata to the java code may parse and process the metadata at compile time or run time method. Simple to understand is to give a specific package name, class, method, member variable labels affixed a special meaning, people can clearly see this label his role and scope, see this machine will achieve this label corresponding to the label service logic (in the case if the business logic).

Second, the role comment

  • Generating documentation, javadoc generation through metadata identification code.

  • Compilation checking, metadata identified by code so that the compiler checks to verify during compilation.

  • Compile-time dynamics, dynamic code processed by the metadata identified at compile time, such as dynamically generated code.

  • Dynamic process, processing dynamic metadata identified by code running runtime, for example using injection reflection Example

The important thing to say three times:

Notes are only metadata and business logic has nothing to do! !

Notes are only metadata and business logic has nothing to do! !

Notes are only metadata and business logic has nothing to do! !

Third, the type of annotation

  • One is Java comes with standard annotation, including @ Override, @ Deprecated and @SuppressWarnings, are used to indicate a rewrite method, indicating a class or method obsolete, indicating a warning to ignore, these notes marked with the compiler device will be checked.

  • A class-membered annotation, annotation metadata annotations are used to define the annotation, including @ Retention, @ Target, @ Inherited, @ Documented, @ Retention annotations are indicated for phase retained, @ Target annotation used to indicate a range, @Inherited used to identify inheritable annotation, @ Documented used to indicate whether javadoc generation.

  • One for the custom annotation can be defined according to their needs annotations, and metadata annotation can be used to annotate the custom annotation. 

Fourth, the yuan notes

  • @Target, - indicates that the annotations are used where. If you do not clear that the comment can be placed anywhere. The following are some of the available parameters. It should be noted: annotation properties are compatible, if you want to annotate all seven properties, excluding one property only, then you need to include all of the attributes defined target. ElementType (ElementType ==> scope range):

    1. CONSTRUCTOR : constructor is used to describe

    2. the FIELD : used to describe the field

    3. LOCAL_VARIABLE : local variables used to describe the

    4. the METHOD : The method described for

    5. The PACKAGE of : a description of the package

    6. The the PARAMETER : parameters used to describe the

    7. The the TYPE : for describing class, interface (including type of annotation), or an enum declaration

  • @ Retention, - the definition of the annotation lifecycle.

         SOURCE      corresponding to the source stage

         CLASS         correspond compilation phase

         RUNTIME      at any time, consists of two phases above

  • @ Documented, - a simple Annotations mark notes, annotations indicating whether the information added to the java documentation.

  • @ Inherited- define the relationship of the notes and subclasses

Yuan notes

effect

The value

Remark

@Target

Specifies the use of local notes

Given below

You can understand that when a comment is @Target comment, this comment was limited use of the scene. Analogy to the label, the label was originally posted to which you want to place on which to place, but because of the presence of @Target, post it on a very specific place, and such can only be posted on the method, the class, method parameters, and so on .

@Retention

Description survival time annotations

Given below

We can in such a way to deepen understanding, @ Retention to give a label to explain when this label that specifies the time posted. @Retention corresponds to a label on the lid of a time stamp, the time stamp indicates the time period label posted.

@Document

Whether notes can be documented

no

uncommonly used

@Inhrited

Description notes can be inherited

no

uncommonly used

Fifth, the implementation notes

Annotations supports only basic types, String and enumerated types. Note that all attributes are defined as a method and allows to provide default values.

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Todo {
   public enum Priority {LOW, MEDIUM, HIGH}
   public enum Status {STARTED, NOT_STARTED}
   String author() default "Yash";
   Priority priority()defaultPriority.LOW;
   Status status() default Status.NOT_STARTED;
}
@Todo(priority = Todo.Priority.MEDIUM, author ="Yashwant", status = Todo.Status.STARTED)
public void incompleteMethod1() {
  //Some business logic is written
  //But it’s not complete yet
}

Sixth, annotation processor

This is the core of notes used, in front of us said so many notes related, that in the end java is how to deal with these annotations it

From getAnnotation we can see into the java.lang.class realized AnnotatedElement method

MyAnTargetType t = AnnotationTest.class.getAnnotation(MyAnTargetType.class);
public final class Class<T> implements java.io.Serializable,
                              GenericDeclaration,
                              Type,
                              AnnotatedElement

A following four methods java.lang.reflect.AnnotatedElement interfaces all program elements (Class, Method, and the Constructor) the parent interface, the program acquired by the reflection target a class AnnotatedElement Thereafter, the program can use the object to Annotation information visit:

  Method 1: <T extends Annotation> T getAnnotation (Class <T> annotationClass): Back to change the existing program element, to specify the type of annotation, annotation if the type does not exist, null is returned.
  Method 2: Annotation [] getAnnotations () : returns all elements present on the annotation program.
     Method 3: boolean is AnnotationPresent (Class annotationClass <extends Annotation?>):. Determining whether contains the specified types of notes on the program element, returns true is present, otherwise returns false
  Method 4: Annotation [] getDeclaredAnnotations () : returns directly present All comments on this element. And other methods in this interface is different, this method ignores inherited annotations. (If no annotations are directly present on this element, an array of length zero is returned.) The caller of the method is free to modify the returned array; this will have no impact on the array returned by other callers

Seven cases using annotations

Tell me what you can jump to the reference in the last two links, thank the author of two articles on this source virtual machine and the underlying implementation to analyze, explain in Spring @Autowire java annotations and notes in @Override implementation principle.

From which we can more deeply appreciate, notes are only metadata and business logic has nothing to do! !

All business logic representatives annotations, and comments are peeled apart itself, after declaring the scope and survival time annotations, by reflection, to obtain the effect of the annotation of the art, and thus the package, class, method, members variable business logic operations.

 

Reference material

Principle Java annotations (easy to understand)

Java annotations analytical works

JAVA annotation mechanism and principle

Spring IOC analytical principle source (@Autowired Detailed principles: identifying attributes and methods) (ii)

Look Java virtual machine from the perspective of polymorphic -> (rewriting override) implementation principle

Published 60 original articles · won praise 57 · views 80000 +

Guess you like

Origin blog.csdn.net/qixinbruce/article/details/89006163