[Reprint Collection] Java annotations

Source: Internet
Author: User
Tags deprecated

Tag: Data cannot be led name let variable about annotation processor param

1, Annotation


Its role is to modify programming elements. What is a programming element? For example: Package, class, constructor method, method, member variable, and so on. Annotation (note) Is that Java provides a way and a way for an element in a meta-program to correlate any information and any metadata (metadata). Annotion (annotation) is an interface that a program can use to get the Annotion object of a specified program element, and then obtain the metadata within the annotation by Annotion object.

Annotation (note) was introduced in JDK5.0 and later versions. It can be used to create documents, track dependencies in code, and even perform basic compile-time checks. In some ways, annotation is used like a modifier and is applied to the declaration of a package, a type, a constructor method, a method, a member variable, a parameter, a local variable. This information is stored in the annotation "name=value" structure pair.

The members of the annotation are declared in the annotation type in the form of a parameterless method. Its method name and return value define the name and type of the member. Here is a specific default syntax: Allows you to declare the default value for any annotation member: A annotation can use Name=value as a value for a annotation member that does not have a default value defined, and of course it can be used name= The value pair overrides the other member's default value. This is somewhat similar to the inheritance attribute of the class, where the constructor of the parent class can be the default constructor for the subclass, but it can also be overridden by the quilt class.

Annotation can be used to associate any information with a program element (class, method, member variable, and so on). It is important to note that there is a basic rule here: Annotation does not affect the execution of program code, regardless of the addition or deletion of Annotation, the code is consistently executed. In addition, while some annotation are accessed at run time through the Java Reflection API approach, the Java language interpreter ignores these annotation when it works. It is the Java virtual machine that ignores the annotation, which causes the annotation type to "not work" in the code, and the information in the annotation type is accessed and processed only by a matching tool. This article will cover the standard annotation and meta-annotation types, and the tools that accompany these annotation types are the Java compilers (and of course they are handled in a special way).

2. What is metadata (meta data):


Metadata is translated from the word metadata, which means "data about data".
There are many functions of meta data, such as: You may have used Javadoc annotations to automatically generate documents. This is one of the meta-data functions. In general, metadata can be used to create documents, keep track of code dependencies, and perform compile-time format checks instead of existing configuration files. If you want to classify the role of metadata, there is no clear definition, but we can according to its role, broadly can be divided into three categories:
1. Writing a document: Generating a document from the metadata identified in the code
2. Code Analysis: Analyze code with metadata identified in code
3. Compile check: The compiler can implement the basic compilation check through the metadata identified in the code
In Java, metadata exists in Java code in the form of tags, and the presence of metadata tags does not affect the compilation and execution of program code, but is used to generate other files or needles that know the description of the running code at run time.
Sum up:
First, the metadata exists in the Java code in the form of a label.
Second, metadata describes the information that is type-safe, that is, the fields within the metadata are explicit types.
Third, metadata requires additional processing by tools outside the compiler to generate additional program parts.
The metadata can exist only at the Java source level, or it can exist inside a compiled class file.

3, annotation and annotation types:


annotation uses the new syntax introduced in java5.0, which behaves much like a modifier such as public and final. Each annotation has a name and a number of members >=0. Each member of the annotation has a name and value (like JavaBean) called the Name=value pair, and name=value loads the annotation information.

The annotation type defines the annotation name, type, and member default values. A annotation type can be said to be a special Java interface whose member variables are restricted, and the new syntax is required when declaring annotation types. When we access annotation through the Java Reflection API, the return value will be an object that implements the annotation type interface, which we can easily access to its annotation members by accessing this object. The following chapters will refer to the 3 standard annotation types contained in the Java.lang package of java5.0.

4, the classification of annotations:


Depending on the number of annotation parameters, we can divide the annotations into three categories:
1. Tag annotations: A annotation type that has no member definition is called a tag annotation. This type of annotation only uses its own presence or not to provide information to us. For example, the following system annotation @override;
2. Single value annotations
3. Full annotations
Based on the usage and use of annotations, we can divide annotation into three categories:
1.JDK built-in system annotations
2. Meta-annotations
3. Custom annotations

5, the system built-in standard notes:


The syntax of annotations is relatively simple, except for the use of the @ symbol, which is basically consistent with the native syntax of Java, with three standard annotations built into the javase, defined in Java.lang:
@Override: A method used to decorate this method that overrides the parent class; ---played a role in assertions.
@Deprecated: Used to modify a method that is obsolete; ---compiler will not encourage the use of this annotated program element.
@SuppressWarnnings: Used to notify the Java compiler against specific compilation warnings.
-----Deprecated has a certain "continuity": if we use this obsolete type or member in code by inheriting or overwriting it, although the inherited or overwritten type or member is not declared as @Deprecated, the compiler still has to call the police.
----Suppresswarning is not a markup annotation. It has a member of type string[], and the value of this member is the forbidden warning name.

Simple description of common parameter values for suppresswarnings annotations:
1.deprecation: Warning when using a class or method that is not in favor of use;
2.unchecked: Warning When an unchecked conversion was performed, such as when using a collection without generics (generics) to specify the type of collection to save;
3.fallthrough: A warning when a Switch block directly leads to the next situation without a break;
4.path: Warning when there is a nonexistent path in the classpath, source file path, etc.;
5.serial: A warning when a SERIALVERSIONUID definition is missing on a serializable class;
6.finally: Any warning when the finally clause does not complete properly;
7.all: Warning about all of these conditions.

The annotation syntax allows the annotation name to be followed by parentheses, where the comma-separated name=value is used to assign values to the members of the annotation.
[Email protected] (value={"Rawtypes", "Unchecked"})

6. Custom annotations


1) define with @interface keyword
(2) annotations contain members, and members are declared in the form of a parameterless method. Its method name and return value define the name and type of the member.
(3) The member assignment is in the form of @annotation (Name=value).
(4) Annotations need to indicate the life cycle of the annotations, the modified target of the annotations, etc., which are realized through meta annotations.
The above syntax is not easy to understand, the following examples to illustrate, this example is the target annotated source code,

@Retention (value = retentionpolicy.runtime)
@Target (value = {Elementtype.annotation_type})
Public @interface Target
{
Elementtype[] Value ();
}
The source code analysis is as follows:
First: Meta annotation @retention, the value of member value is retentionpolicy.runtime.
Second: meta-annotation @target, member value is a number of groups, with the form of {}, the value is Elementtype.annotation_type
Third: The member name is value and the type is elementtype[]
Also, be aware that if the member name is value, it can be abbreviated during the assignment. You can also shorthand if the member type is an array, but only one element is assigned. As the abbreviated form above is:
@Retention (Retentionpolicy.runtime)
@Target (Elementtype.annotation_type)

7. The life cycle of annotations


The definition syntax for annotations already says that annotations need to indicate the life cycle of annotations, which are implemented through meta annotations. And this meta-annotation is:
Public @interface Retention
{
Retentionpolicy value ();
}
The value of the retention annotation is the retentionpolicy of the enum type. There are several situations:
(1) Source: Annotations are retained only in the source file, and when the Java file is compiled into a class file, the annotations are discarded. Annotations is to being discarded by the compiler.
(2) Class: Annotations are persisted to the class file, and the JVM is discarded when it loads the class file. This is the default life cycle.
Annotations is to being recorded in the class file by the compiler,
But need is retained by the VM at run time. This is the default behavior.
(3) RUNTIME: Annotations are not only saved to the class file, but after the JVM loads the class file, it still exists, saved to the class object, and can be obtained by reflection.
Annotations is to being recorded in the class file by the compiler and
Retained by the VM at run time, so they may be read reflectively.

8. Modified target of annotations


The definition syntax for annotations has already been stated: Annotations need to indicate the adornment target of the annotations, which is implemented through meta annotations. And this meta-annotation is:
Public @interface Target
{
Elementtype[] Value ();
}
The value of this annotation is the enum type ElementType. There are several situations:
(1) Type: Refers to annotations that are used on classes, interfaces (including annotations), or enums.
(2) field: Refers to the annotation used in the field attribute, also including the enum constant.
(3) Method: Refers to an annotation used on a method declaration.
(4) PARAMETER: Refers to the annotations used on the parameters,
(5) CONSTRUCTOR: Refers to annotations that are used in the constructor.
(6) Local_variable: Refers to annotations that are used on local variables.
(7) Annotation_type: Refers to the meta-annotations used on annotations
(8) Package: Refers to annotations that are used on packages.

9, the bottom implementation of annotations


Define an annotation:
@Retention (Retentionpolicy.runtime)
@Target (Elementtype.type)
Public @interface Cache
{
String value () default "cache";
}
Analyze its bytecode with javap-verbose, as shown in:

Analyzing the above bytecode, we can conclude that:
First: public interface cache extends Java.lang.annotation.Annotation, stating that the cache annotations are inherited from annotation and still interface.
Second: Public abstract java.lang.String value (), which indicates that the value method is an abstract type.

10. Inheritance of annotations


@Inherited used to describe annotation can be inherited
If a annotation type that uses the @inherited modifier is used for a class, the annotation will be used for subclasses of that class.
Note: @Inherited the annotation type is inherited by subclasses of the class being labeled. The annotation is not inherited from an interface, and the method does not inherit from the overloaded method annotation
@Target (Elementtype.type)
@Retention (Retentionpolicy.runtime)
@Documented
@Inherited
Public @interface Annonitiontargettest {
}

11. Note Processor Class

Interface Java.lang.reflect.AnnotatedElement, its implementation class:

Java.lang.Class class,
Java.lang.reflect.Filed class,
Java.lang.reflect.Constructor class,
Java.lang.reflect.Method class,
Java.lang.Package class
Related methods:
<t extends annotation> T getannotation (class<t> annotationclass); Returns an annotation of the specified type that exists on the program element, or null if the type annotation does not exist.
Annotation[] Getannotations (); Returns all annotations that exist on the program element.
Boolean isannotationpresent (Class<t extends annotation> annotationclass); Evaluates whether the program element contains annotations of the specified type, returns True if present, or false otherwise.
Annotation[] Getdeclaredannotations (); Returns all annotations that exist directly on this element. Unlike other methods in this interface, the method ignores inherited annotations. (if no comment exists directly on this element, an array of zero length is returned.) The caller of the method can arbitrarily modify the returned array, which does not have any effect on the array returned by other callers.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

PS: Content from the following blog, Invasion and deletion.

Http://www.cnblogs.com/peida/archive/2013/04/23/3036035.html

http://swiftlet.net/archives/1906

Http://www.cnblogs.com/imeng/p/4023125.html

[Reprint Collection] Java annotations

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.