Deep understanding of Java annotation Principles __java

Source: Internet
Author: User
deep understanding of Java annotation Principles


* Use of annotations

Annotations (Annotation) is a new feature introduced by JDK1.5, contained in the Java.lang.annotation package, is a bit of meta information attached to the code that links the external information of a class to internal members, parsing and using it at compile, runtime. Java has built-in annotations (such as @override, @Deprecated, and so on) and supports custom annotations, and some well-known frameworks Struts, Hibernate, spring have their own custom annotations implemented, and can define annotations for use.

Annotation is very similar to the modifiers such as public and final. Each annotation has a >=0 name and number of members. The members of each annotation have names and values called Name=value pairs (just like JavaBean), Name=value loaded with annotation information.


Annotation Class (Java.lang.reflect.Annotation):

The annotation type defines the annotation name, type, and member default values. A annotation type can be said to be a special Java interface, its 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, and we can easily access its annotation members by accessing the object. The following sections refer to the 3 standard annotation types included in the Java.lang package in java5.0. Its subclasses are shown in the following illustration:


Annotation Processor Class library (java.lang.reflect.AnnotatedElement):

Java uses the annotation interface to represent the annotations in front of the program element, which is the parent interface for all annotation types. In addition, Java in the Java.lang.reflect package of the new Annotatedelement interface, which represents the program can accept the annotation of the program elements, the interface is mainly the following implementation classes (as shown in the following figure):

Class: Classes define
Constructor: constructor definition
Field: Tired member variable definition
Method: Methods definition for a class
Package: Package definition for Class

The Java.lang.reflect package contains a number of tool classes to implement the reflection function, in fact, the Java.lang.reflect package provides a reflection API that expands the ability to read run-time annotation information. When a annotation type is defined as a run-time annotation, the annotation can be visible at runtime, and the annotation that is stored in the class file when the class file is loaded is read by the virtual machine.
The Annotatedelement interface is the parent interface of all program elements (class, method, and constructor), so that after the program obtains the Annotatedelement object of a class by reflection, The program can invoke the following four methods of the object to access the annotation information:

Method 1:<t extends Annotation> T getannotation (class<t> annotationclass): Returns a specified type of annotation that exists on the modifier element, if the type annotation does not exist, NULL is returned.
Method 2:annotation[] Getannotations (): Returns all annotations that exist on the program element.
Method 3:boolean is annotationpresent (class<?extends annotation> annotationclass): Determines whether a specified type of annotation is included on the program element, and returns true if it exists. otherwise returns false.
Method 4:annotation[] Getdeclaredannotations (): Returns all comments 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 is free to modify the returned array, which does not have any effect on the array returned by the other caller.


* Annotation Type

The general format for annotations is the [modifier] @interface [name]{element}, the element is a method declaration without a method body, and can have default values, such as the @target annotation as follows:

@Documented
@Retention (retentionpolicy.runtime)
@Target (elementtype.annotation_type) public
@ Interface Target {
    elementtype[] value ();
}

The function of the meta annotation is to annotate other annotations. Java5.0 defines 4 standard meta-annotation types that are used to provide descriptions of other annotation types. Java5.0 defined meta Annotations:
1. @Target,
2. @Retention,
3. @Documented,
4. @Inherited
These types and the classes they support can be found in the Java.lang.annotation package. Let's take a look at the role of each meta annotation and the instructions for using the corresponding argument.

@Target:

@Target describes the range of objects that annotation modifies: annotation can be used for packages, types (classes, interfaces, enumerations, annotation types), type members (methods, construction methods, member variables, enumeration values), Method parameters and local variables (such as loop variables, catch parameters). Using target in a annotation type of declaration can make it more explicit about the target that it modifies.

Role: Used to describe the scope of use of annotations (i.e., where the described annotations can be used)

The value (ElementType) is derived from an enumeration type element in Java.lang.annotation.ElementType:

1.CONSTRUCTOR: Used to describe the builder
2.FIELD: Used to describe the domain
3.local_variable: Used to describe local variables
4.METHOD: Used to describe the method
5.PACKAGE: Used to describe the package
6.PARAMETER: Used to describe parameters
7.TYPE: Used to describe classes, interfaces (including annotation types) or enum declarations

@Retention:

@Retention defines how long the annotation is retained: Some annotation only appear in the source code and are discarded by the compiler, while others are compiled into the class file ; The annotation that are compiled in the class file may be ignored by the virtual machine, while others will be read when class is loaded (note that the class is not enforced because annotation is separated from the class in use). Use this meta-annotation to limit the lifecycle of annotation.

Role: Indicates the level at which the annotation information needs to be saved to describe the life cycle of the annotation (i.e., the scope of the described annotation is valid)

Value (Retentionpoicy) is derived from the Java.lang.annotation.RetentionPolicy enumerated type value:

1.SOURCE: Valid in the source file (that is, source file retention)
2.CLASS: Valid in class file (that is, class reservation)
3.RUNTIME: Valid at run time (that is, run-time reservation)

@Documented:

@Documented A common API that describes other types of annotation should be used as members of the annotated program, so it can be documented by tools such as Javadoc. Documented is a tagged annotation with no members.

@Inherited:

A @Inherited meta annotation is a markup annotation @Inherited illustrates that a labeled type is inherited. If a annotation type using the @inherited modifier is used for a class, the annotation will be used for subclasses of that class.

Note: The @Inherited annotation type is inherited by subclasses of the annotated class. The class does not inherit annotation from the interface it implements, and the method does not inherit annotation from the method it overloads.

The reflection API enhances this inheritance when the retention of the annotation @inherited annotation type callout is retentionpolicy.runtime. If we use Java.lang.reflect to query a @inherited annotation type of annotation, the reflection code check expands to work: Check class and its parent class until the specified annotation type is found. Or to the top level of the class inheritance structure.
* Annotation Implementation Instance implementation annotation requires three conditions: annotation declaration, element with annotation, action annotation to make it work (annotation processor).

set a MyTag annotation class:

Import Java.lang.annotation.ElementType;
Import java.lang.annotation.Inherited;
Import java.lang.annotation.Retention;
Import Java.lang.annotation.RetentionPolicy;
Import Java.lang.annotation.Target;

@Target ({Elementtype.method,elementtype.field})
@Inherited
@Retention (retentionpolicy.runtime)
Public @interface MyTag {

	String name () default "car";
	int size () default;


Define an entity car class:
public class Car {

	private String name;
	private int size;
	Public String GetName () {return
		name;
	}
	public void SetName (String name) {
		this.name = name;
	}
	public int GetSize () {return
		size;
	}
	public void setSize (int size) {
		this.size = size;
	}
	
	Public car () {
		
	} public car
	(String name, int size) {
		this.size = size;
		this.name = name;
	@Override public
	String toString () {return
		' car [name=] + name +, size= ' + size + '] ';
	}
	

Define a class Annotationdemo class that uses annotations:
public class annotationdemo{
	
	@MyTag (name = "Audi", size = ten)
	private car car;

	Public Car Getcar () {return car
		;
	}

	public void Setcar (car car) {
		This.car = car;
	}

	@Override public
	String toString () {return
		' Annotation [car=] + car + '] ';
	}


The class Annotationproccessor class that defines an action note that makes annotations work:
Import Java.lang.reflect.Field;

public class Annotationproccessor {
	
	public  static void annoprocess (Annotationdemo annotation) {for
		
		Field Field:annotation.getClass (). Getdeclaredfields ()) {
			if (field.isannotationpresent (Mytag.class)) {  // If there is a MyTag label
				mytag mytag = field.getannotation (mytag.class);
				Annotation.setcar (New Car (Mytag.name (), Mytag.size ()));
	}} public static void Main (string[] args) {
		Annotationdemo ann = new Annotationdemo ();
		Annoprocess (Ann);
		System.out.println (Ann.getcar ());
		
	}





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.