[Reprint] Java Advanced Series - notes (Annotations)

Java Advanced Series - notes (Annotations)

I. INTRODUCTION

This part of this series we will introduce version introduced in Java 5 generics and enumerated in addition to another powerful feature: comment to be viewed as a special interface.

Annotations are a special kind of meta-data, it can be associated with different elements of the Java language and structure. Interestingly, most of the local model using XML descriptor in the Java ecosystem, annotation made a great contribution to the elimination of these XML descriptors. It notes the introduction of a new type of security and very robust configuration and personalization technologies.

Second, the comment as a special interface

As we mentioned in the foregoing, as associated metadata annotations to the Java language and the different elements.

Notes annotation element itself it does not cause any direct impact. However, relying on notes and the way it is defined, they can be Java compiler (the best example is our previous article notes used @Override notes), annotation processor and run-time code using reflection and other virtual machines introspection techniques.

Let's look at a simple statement notes:

public @interface SimpleAnnotation {
}

 

@interface keyword introduces a new annotation type, which is why the notes can be viewed as a special interface, annotation can declare default values ​​and attributes have no default values, such as:

public @interface SimpleAnnotationWithAttributes {
    String name();
    int order() default 0;
}

 

If annotation declares that property has no default value, then the annotations are in the application should provide annotation attribute values ​​place.

@SimpleAnnotationWithAttributes(name = "new annotation")

 

For convenience, if only a comment attribute and name attribute is value, then the name of the property can be omitted, such as:

public @interface SimpleAnnotationWithValue {
    String value();
}

 

The above statement of this annotation can be in the following ways to use:

@SimpleAnnotationWithValue("new annotation")

  

Notes also has some limitations, the use of annotations in some cases may be less convenient.

  • First, the comment does not support any Inheritance: Annotations can not inherit other comments.

  • Secondly, the form can not be encoded using the new keyword to create annotation instances.

  • Third, the statement notes only basic data type attributes, String or Class <?> Type and array.

  • Fourth, the notes are not allowed declare methods and constructors.

Third, annotation and retention policies (Retention Policy)

Each annotation has been a feature called retention policy (Retention Policy), which is how to keep a set of annotation strategy combination of enumeration (RetentionPolicy type). Retention policies can be set to one value or less.

Tactics description
CLASS The compiler annotations are recorded in the class file, but is not required at run-time virtual machine reservations (ie there is no run-time)
RUNTIME The compiler annotations are recorded in the class file and are retained in the virtual machine is running, so you can get through reflection
SOURCE Compiler annotations are discarded (i.e., retained only annotations in the source code, class file does not exist)

Retention policy has a crucial influence on the Annotations can be used when handling. Retention policies can be set by using @Retention comment. such as:

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention( RetentionPolicy.RUNTIME )
public @interface AnnotationWithRetention {
}

  

Set annotation retention policy to comment RUNTIME will ensure the presence of the compilation process and the application is running.

Fourth, the notes and the element type (ElementType)

Another feature is annotated each annotated element must have a type that can be applied. Somewhat similar to a retention policy, the element type is defined as a set of possible elements of an enumeration type (ElementType).

Element Type description
ANNOTATION_TYPE Annotations may be used to indicate the annotation type declaration (applied additional annotations)
CONSTRUCTOR Annotations can be used to indicate the constructor declaration
FIELD Annotations can be used to indicate the field / fields (including enumeration constants) Statement
LOCAL_VARIABLE Annotations can be used to indicate a local variable declaration
METHOD Annotations can be used to indicate the method declaration
PACKAGE Annotations can be used to indicate the package declaration
PARAMETER Annotations can be used to indicate the parameter declaration
TYPE Annotations may be used to indicate class, interface (including annotation type), enumeration type declaration

Further, in addition to these elements of the type described above, Java 8 version introduces two new annotation type element may be used.

Element Type description
TYPE_PARAMETER Marked notes can be written in the type of a variable declaration statement
TYPE_USE It indicates that the notes can be written using any type of statement (eg: declaration, generics and casts statement)

And comparison of retention policies, annotations can be used @Target annotation declares multiple elements associated with the type more with it. such as:

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

@Target({ElementType.FIELD, ElementType.METHOD})
public @interface AnnotationWithTarget {
}

 

 

In most cases, all the notes you want to create the policy should specify the element type and reservations can be useful.

Fifth, notes and inheritance (Annotations and inheritance)

In Java, there is a very important link between the declaration notes and inheritance. By default, the subclass can not inherit the parent class notes declared, however, there is a way that can be specified by using @Inherited annotation pass notes in class hierarchy. such as:

@Target( { ElementType.TYPE } )
@Retention( RetentionPolicy.RUNTIME )
@Inherited
@interface InheritableAnnotation {
}

@InheritableAnnotation
public class Parent {
}

public class Child extends Parent {
}

 

In this example, we declared @InheritableAnnotation notes in the parent class can be inherited by subclasses.

Six, can repeat notes (Repeatable annotations)

So far we have not discussed a limited version and additional notes related to the previous 8 Java, that is, the same notes in the same place can only occur once, can not be repeated many times. Java 8 to relax this restriction by providing repeated notes of support. such as:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RepeatableAnnotations {
RepeatableAnnotation[] value();
}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Repeatable( RepeatableAnnotations.class )
public @interface RepeatableAnnotation {
    String value();
};

@RepeatableAnnotation("repeatition 1")
@RepeatableAnnotation("repeatition 2")
public void performAction() {
    // Some code here
}

 

 

Although repeat annotations in Java 8 needs to do some work to make annotations can be reused (use @Repeatable), but the end result is worth it: more concise and compact commented code.

Seven annotation processor (Annotation processors)

Java compiler called annotation processor supports a special type of plug-in (using -processor command-line arguments), it can handle annotation at compile time. Annotation processor can analyze the role of annotations (perform static code analysis), create additional Java source file or resource (can be compiled and processed), or change the annotated code.

In the annotation tells the compiler that can be annotated processor applications and processes, retention policies (Retention Policy) has played a pivotal role.

Annotation processor is widely used, but to write a comment about the processor needs some knowledge of how Java compilers work and compilation process itself.

VIII annotation configuration greater than convention (Annotations and configuration over convention)

Convention is larger than the configured a software design practice and the practice is designed to simplify the development process, developers need to follow some simple rules (or agreement). For example, some of the MVC framework convention will follow the controller on the controller directory (or package), some ORM frameworks often follow the convention to find entity classes in the model directory and get table names from their respective classes.

On the other hand, notes created a different design practice whereby all based on explicit configuration. In our example above mentioned terms, @ Controller annotation can clearly mark any class that may be associated with a database table as a controller, @ Entity annotation. Notes also benefit from the fact that the notes of scalability, can have additional properties and limited types of specific elements. Java compiler will enforce the improper use of annotations and configuration problems have long found errors at compile time.

Nine, when to use annotations

Notes in fact everywhere: Java standard library has a lot, basically every Java specification contains notes. Whenever you need to attach metadata associated with your code, annotations are simple and direct way.

Interestingly, Java community are constantly working to develop common public through a variety of semantic concepts and technical standards (for more information, see JSR-250 specification) annotations. Currently, the standard Java library contains the following comments.

annotation description
@Deprecated It indicates that the marked element has expired and should no longer be used. Whenever a program is to use the annotation annotated, class or field (domain), the compiler generates a warning.
@Override Hints to the compiler that element is intended to cover the elements declared in the parent class.
@SuppressWarnings It instructs the compiler to suppress the warning generated by other means.
@SafeVarargs When applied to a method or constructor declaration code does not perform its potentially unsafe operation of a variable parameter. When you use this annotation type, it will be suppressed with a warning about the use of variable parameters unchecked.
@Retention Specify how to keep annotations are marked.
@Target Specifies the marked annotation can use those elements in Java
@Documented That the use of the annotation tool Javadoc recording element can be used (by default, annotations are not included in the Javadoc)
@Inherited Show annotation type can be inherited from the parent class

Java 8 release of version also adds several new comment.

annotation description
@FunctionalInterface It indicates the type of declaration is a function of the interface in accordance with specification defines the Java language.
@Repeatable Show notes marked can be applied multiple times in the same place.

X. Summary

This article tells us about some of the notes and related content, by reading this article we can generally understand annotation can be used as a special interface, in defining a new comment is that we need to specify retention policy and element type annotations. We also explains how to make annotation subclass inherits the parent class and how to declare repeatable comment. Of course, we also talk about some of the concepts in the annotation processor and annotation configuration is greater than the compliance agreement. Next, we will discuss how to effectively write method, so stay tuned.

Guess you like

Origin www.cnblogs.com/jinanxiaolaohu/p/11275767.html