Full parsing of Java annotations

Source: Internet
Author: User

1. Basic syntax

The annotation definition looks much like the definition of an interface. In fact, as with any other interface, annotations will be compiled into class files.

@Target (Elementtype.method)

@Retention (Retentionpolicy.runtime)

Public @interface Test {}

In addition to the @ symbol, the definition of @Test is much like an empty interface. When defining annotations, some meta annotations (meta-annotation) are required, such as @target and @retention

@Target used to define where the annotation will be applied (such as a method or a field)

@Retention is used to define the level at which annotations are available, in source code, in the class file (class), or at run time (runtime)

In annotations, some elements are typically included to represent certain values. The program can take advantage of these values when parsing processing annotations. Annotations without elements are called tag annotations (marker annotation)

Four meta annotations, meta annotations are dedicated to annotating other annotations, so the target value for these four annotations is Elementtype.annotation_type

Annotations Description
@Target Indicates where the annotation can be used, defined by the ElementType enumeration
CONSTRUCTOR: Declaration of the constructor
Field: Domain declarations (including enum instances)
local_variable: local variable declaration
Method: Methods Declaration
Package: Packet declaration
PARAMETER: Parameter declaration
Type: class, interface (including annotation type) or enum declaration
Annotation_type: annotation declaration (applied to another annotation)
Type_parameter: type parameter declaration (1.8 newly added)
Type_use: Declaration of type Use (1.8 new addition)
PS: When the annotation does not specify a target value, this annotation can use any element above, which is the type above
@Retention Indicates the level at which the callout information needs to be saved, as defined by the Retentionpolicy enumeration
Source: Annotations will be discarded by the compiler (this type of annotation information will only be kept in the source code, the source is compiled, the annotation information will be discarded, will not be kept in the compiled class file)
Class: Annotations are available in the class file but are discarded by the VM (this type of annotation information is kept in the source and class files and is not loaded into the virtual machine (JVM) at execution time)
RUNTIME:VM will also retain the annotation information at runtime, so the information of the annotations can be read through the reflection mechanism (source code, class file, and annotated information when executing)
PS: When annotations do not have a retention value defined, the default value is class
@Documented Indicates that annotations are included in the JAVAAPI document
@Inherited Allow subclasses to inherit annotations from parent classes

2. Annotation elements

– The types of annotation elements available are as follows:

– All basic types (Int,float,boolean,byte,double,char,long,short)

–string

–class

–enum

–annotation

– Arrays of the above types

If other types are used, the compiler will make an error. It is also not allowed to use any wrapper type. Annotations can also be types of elements, that is, annotations can be nested.

The modifier for the element, only public or default.

– Default value Limit

The compiler is a bit too picky about the default value of the element. First, the element cannot have an indeterminate value. In other words, the element must either have a default value or provide the value of the element when using annotations.

Second, for elements of non-primitive types, whether they are declared in the source code or defined by default in the annotation interface, you cannot use NULL as the value. This is the limit, which makes it difficult for the processor to represent the presence or absence of an element, because in each annotation declaration, all elements are present and have corresponding values. To circumvent this restriction, you can define only a few special values, such as an empty string or a negative number, to indicate that an element does not exist.

@Target (Elementtype.method)

@Retention (Retentionpolicy.runtime)

Public @interface Mocknull {

public int id () default-1;

Public String description () default "";

}

3. Shortcuts

What is a shortcut? First look at the controller annotations in SPRINGMVC

@Target ({elementtype.type})

@Retention (Retentionpolicy.runtime)

@Documented

@Component

Public @interface Controller {

String value () default "";

}

You can see that target is applied to classes, interfaces, annotations, and enumerations, and the retention policy is runtime and has a string type of value element. The usual use of the time is basically the same:

@Controller ("/your/path")

public class Mockcontroller {}

This is the shortcut, omitting this syntax for name-value pairs. Here is a detailed explanation:

An element named value is defined in the annotation, and when the annotation is applied, if the element is the only one that needs to be assigned, then it is not necessary to use this syntax for the name-value pair, but only the values required by the value element in parentheses. This can be applied to any element of the legal type, of course, which restricts the element name to be value.

4. JDK1.8 Annotation Enhancements

Type_parameter and Type_use

More than two enumeration members, Type_parameter and Type_use, are ElementType in JDK1.8, and they are all used to qualify which type can be annotated. For example, if you want to annotate the type parameters of a generic type:

public class annotationtypeparameter< @TestTypeParam t> {}

Then, when defining @testtypeparam, you must set the Elementtype.type_parameter in @target to indicate that this annotation can be used to label type parameters. For example:

@Target (Elementtype.type_parameter)

@Retention (Retentionpolicy.runtime)

Public @interface Testtypeparam {}

Elementtype.type_use is used to label various types, so the above example can also change Type_parameter to Type_use, an annotation is set to Type_use, and as long as it is a type name, it can be annotated. For example, the following annotation definitions are available:

@Target (Elementtype.type_use)

@Retention (Retentionpolicy.runtime)

Public @interface Test {}

Then the following usage annotations are possible:

list< @Test comparable> list1 = new arraylist<> ();

list<? Extends comparable> list2 = new arraylist< @Test comparable> ();

@Test String text;

Text = (@Test String) New Object ();

Java.util. @Test Scanner Console;

console = new [email protected] Scanner (system.in);

PS: The above @test annotations are on the right side of the type, to be aware of the enumeration members before 1.8, for example:

@Test java.lang.String text;

In the above example, it is obvious that the text variable is being annotated, so using the current @target will compile the error, plus elementtype.local_variable.

@Repeatable annotations

@Repeatable Note is a new addition to the JDK1.8, from the name of the meaning can probably guess his meaning (repeatable). You can repeat the same annotations in the same place. Example:

@Target (Elementtype.type)

@Retention (Retentionpolicy.runtime)

Public @interface Filter {

String [] Value ();

}

Use the following annotations as follows:

@Filter ({"/admin", "/main"})

public class Mainfilter {}

A different style:

@Filter ("/admin")

@Filter ("/main")

public class Mainfilter {}

Before JDK1.8, there was no way to reach this "style", using 1.8, you can define @filter as follows:

@Target (Elementtype.type)

@Retention (Retentionpolicy.runtime)

@Repeatable (Filters.class)

Public @interface Filter {

String value ();

}

@Target (Elementtype.type)

@Retention (Retentionpolicy.runtime)

Public @interface Filters {

Filter [] Value ();

}

This is actually the compiler's optimization, which tells the compiler when using @repeatable, uses @filters as a container for collecting duplicate annotations, and each @filter stores the specified string values.

JDK1.8 adds Getdeclaredannotationsbytype and Getannotationsbytype to the Annotatedelement interface, and looks for a container for repeating annotations when specifying @repeatable annotations. Getdeclaredannotation and getannotation do not handle @repeatable annotations as opposed to. Examples are as follows:

@Filter ("/admin")

@Filter ("/filter")

public class Filterclass {

public static void Main (string[] args) {

class<filterclass> filterclassclass = Filterclass.class;

filter[] Annotationsbytype = Filterclassclass.getannotationsbytype (Filter.class);

if (annotationsbytype! = null) {

for (Filter Filter:annotationsbytype) {

System.out.println (Filter.value ());

}

}

System.out.println (Filterclassclass.getannotation (Filter.class));

}

}

The logs are as follows:

/admin

/filter

Null

Original article reproduced please specify the Source: Java Annotations Comprehensive analysis

original articles, reproduced please specify: reproduced from the Concurrent programming network –ifeve.com This article link address: Java annotations Comprehensive analysis

http://ifeve.com/java-annotation/

Java Annotations full Parse (GO)

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.