Java Annotations Detailed

Source: Internet
Author: User

1. Understanding Annotations

We need to learn a little more about JDK 5.0 's new annotation (Annotation) technology because spring supports @aspectj, and @aspectj itself is a JDK 5.0-based annotation technology. So learning the annotated knowledge of JDK 5.0 helps us to better understand and Master spring's AOP technology.

For Java developers, when writing code, in addition to the source program, we use the Javadoc tag to annotate classes, methods, or member variables so that the Javadoc tool can be used to generate Javadoc documents that match the source code. These javadoc tags, such as @param, @return, and so on, are annotation tags that provide annotated information for third-party tools that describe program code. Friends who have used Xdoclet will be more impressed, like struts, hibernate provide xdoclet tags, and use them to quickly generate the corresponding program code configuration file.

JDK5.0 annotations can be seen as the extension and development of Javadoc tags and xdoclet tags. In JDK5.0, we can customize these tags and get the annotations in the class in the reflection mechanism of the Java language to accomplish certain functions.

Annotations are collateral information for the code, which follows a basic principle: annotations do not directly interfere with the operation of the program code, and the code works correctly regardless of adding or removing annotations. The Java language interpreter ignores these annotations, and the third-party tool is responsible for processing the annotations. Third-party tools can use annotations in the code to indirectly control the operation of program code, which reads the annotated information through the Java reflection mechanism and changes the logic of the target program based on that information, which is the approach that spring AOP takes to provide support for @aspectj.

The syntax of annotations is simple, except for the use of the @ symbol, which is basically consistent with the inherent syntax of Java, with three annotations built into Java, defined in the Java.lang package.

@Override: Can only be used on the method, to tell others that this method is to rewrite the parent class.

@Deprecated: It is recommended that others do not use the old API, when compiling will be used to generate a warning message, can be set in the program all the elements.

@SuppressWarnings: Indicates that some improper compiler warning messages are turned off.

2. Defining annotations

The following is an instance of defining annotations.

@Target (Elementtype.type)
@Retention (Retentionpolicy.runtime)
@Documented
@Inherited
Public @interface Description {

String value ();
}

The @interface is a keyword that must be defined as @interface when designing a annotations, and not with a class or interface keyword. All annotation classes are implicitly inherited from Java.lang.annotation.Annotation, and annotations do not allow explicit inheritance to other interfaces.

An annotation can have more than one member, and a member declaration and an interface method declaration are similar, where we define only one member, and the declaration of a member has the following limitations:

A) members are declared in a non-argument-no-throw exception, such as Boolean value (String str), Boolean value (), throws exception, and so on, which are illegal;

b) You can specify a default value for a member by default, such as String level (), default "Low_level", and "int High" () default 2 is legal, and of course you can not specify a default value;

c) member types are restricted, and valid types include primitive types and their enclosing classes, String, class, enums, annotation types, and array types of the above types. such as Forumservice value (), List foo () is illegal.

d) If the annotation has only one member, the member name must be named value (), and the member name and assignment number (=) can be ignored when used, such as @description ("instance with annotations"). When an annotation class has more than one member, an assignment number is not used if only the value member is assigned, and if multiple members are assigned at the same time, you must use an assignment number, such as @declareparents (value = "Naivewaiter", Defaultimpl = Smartseller.class).

e) Note Classes can have no members, annotations without members are referred to as identity annotations, and the interpreter processes to identify the presence or absence of annotations;

The annotation definition contains four meta-annotations, @target, @Retention, @Documented, @Inherited, respectively. The functions of the meta-annotations are as follows:

1) @Target

Indicates where the annotation is used, and the possible elemenettype parameters include:

The Øelemenettype.constructor constructor declaration.

Øelemenettype.field domain declarations (including enum instances).

Øelemenettype.local_variable local variable declarations.

Øelemenettype.method method declaration.

Øelemenettype.package Package declaration.

The Øelemenettype.parameter parameter declaration.

Øelemenettype.type class, interface (including annotation type) or enum declaration.

2) @Retention

Indicates at what level the annotation information is saved. The optional retentionpolicy parameters include:

Øretentionpolicy.source annotations are discarded by the compiler.

Øretentionpolicy.class annotations are available in the CLASS file, but are discarded by the VM.

Øretentionpolicy.runtime VMS will also retain annotations at run time, so the information of annotations can be read through the reflection mechanism.

To cite an example, such as @override inside the retention set to source, compiled successfully do not have the information of these checks, on the contrary, the @Deprecated inside the retention set to runtime, indicating that in addition to the compile will warn us of the use of which was Deprecated method, you can also find out whether the method is deprecated at the time of execution.

3) @Documented

Include this note in the Javadoc

4) @Inherited

Allow subclasses to inherit annotations from parent class

3. Using annotations

The following is an example of using annotation annotations.

@Description (value= "instance using annotations")
public class Testannotation {

}

Use the syntax of annotations:@< annotation name > (< member name 1>=< member value 1>,< member name 1>=< member value 1>,...)

If the member is an array type, it can be assigned through {}, such as the members of the Boolean array can be set to {true,false,true}. Here are some examples of annotation annotations:

1) Multi-member annotations

@AnnoExample (id= 2868724, synopsis = "Enable Time-travel", engineer = "Mr Peabody")

2) A member's note, the member name is value

You can omit the member name and the assignment symbol: @Copyright ("Right Reserved")

@Copyright ("Bookegou.com All Right Reserved")

3) No member annotations

@Override

@Override

4) annotations with members as arrays of strings

@SuppressWarnings (value={"Unchecked", "Fallthrough"})

@SuppressWarnings (value={"Unchecked", "Fallthrough"})

5) annotation with member as annotation array type

@Reviews ({@Review (grade=review.grade.excellent,reviewer= "DF"),

@Review (grade=review.grade.unsatisfactory,reviewer= "eg",

Comment= "This method needs an @Override annotation")})

@Reviews ({@Review (grade=review.grade.excellent,reviewer= "DF"),

@Review (grade=review.grade.unsatisfactory,reviewer= "eg",

Comment= "This method needs an @Override annotation")})

@Reviews annotations have a member of the @review annotation array type, @Review the annotation type has three members, where reviewer, comment are string types, but comment has a default value, and grade is a member of the enumeration type.

4. Parsing annotations

The following is an example of parsing annotations.

public class Parseannotation {

public static void Main (string[] args) throws exception{
Final Class cls = Class.forName ("com.annotation.TestAnnotation");
Final method[] Method = Cls.getmethods ();

To determine if there are annotations of the specified annotation type
if (Cls.isannotationpresent (Description.class)) {
Returns annotations of the specified type according to the annotation type
Description des = (Description) cls.getannotation (Description.class);
SYSTEM.OUT.PRINTLN ("Note description:" + des.value ());
}
}
}

The output results are as follows:

Annotation Description: Using an instance of an annotation

As mentioned earlier, annotations do not directly affect the operation of the program, but third-party programs or tools can use the annotations in the code to complete special tasks, indirect control program operation. For annotations of the Retentionpolicy.runtime retention period, we can access the annotations in the class through the reflection mechanism.

In JDK5.0, reflective objects such as package, Class, Constructor, method, and field have new ways to access annotation information: <t extends Annotation>t getannotation ( Class<t> Annotationclass), which supports direct return of annotation objects via generics.

Here is an example:

1. Define an annotation

Package Annotation;import Java.lang.annotation.elementtype;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import java.lang.annotation.target;/*** defines an annotation * * * @author jiqinlin**/// There are four meta annotations in Java that are specifically responsible for annotating other annotations, such as the following//@Retention meta annotations, indicating at what level the annotation information (life cycle) needs to be saved. Optional retentionpoicy parameters include://retentionpolicy.source: Stuck in Java source file, compiler discarded// Retentionpolicy.class: Stays in the CLASS file, but is discarded by the VM (default)//retentionpolicy.runtime: In-memory bytecode, the VM will also retain annotations at run time, so the information of the annotations can be read through the reflection mechanism/ /@Target meta Note, the default value is any element that indicates where the annotation is used. The available ElementType parameters include//elementtype.constructor: constructor declaration//elementtype.field: Member variables, objects, attributes (including enum instances)//elementtype.local_ VARIABLE: local variable declaration//elementtype.method: Method declaration//elementtype.package: Package declaration//elementtype.parameter: Parameter declaration// Elementtype.type: Classes, interfaces (including annotation types) or enum declarations//@Documented include annotations in Javadoc//@Inheried allow subclasses to inherit annotations @retention in the parent class ( Retentionpolicy.runtime) @Target ({elementtype.method, elementtype.type}) public @interface myannotation {// Add an attribute to the annotation string color (); String value () default "I am AAA"; Provide default value for property int[] Array () default {1, 2, 3}; Gender Gender () default Gender.man; Add an enumeration metaannotation metaannotation () default @MetaAnnotation (Birthday = "My date of birth is 1988-2-18");}

2. Define Dependencies

Package annotation;/*** enumeration, add enum attribute in mock Note * * **/public enum Gender {man {public String getName () {return "male";}},women {public String GetName () {return "female";}}; Remember there was ";" Public abstract String GetName ();}

  

Package annotation;/*** defines an annotation that adds annotation properties to the mock annotation * **/public @interface metaannotation {String birthday ();}

3. Define test procedures

The package annotation;//invokes the annotation and assigns the value @myannotation ([email protected] (Birthday = "My date of birth is 1988-2-18"), color= "Red", array={23, () public class Annotationtest {public static void main (string[] args) {//Check if class Annotationtest contains @myannotation annotation if ( AnnotationTest.class.isAnnotationPresent (Myannotation.class)) {//If present, get annotations myannotation annotation = (myannotation) AnnotationTest.class.getAnnotation (Myannotation.class); System.out.println (annotation);//Get annotation attribute System.out.println (Annotation.color ()); System.out.println (Annotation.value ());//array int[] Arrs = Annotation.array (); for (int arr:arrs) {System.out.println ( ARR);} Enumeration Gender gender = Annotation.gender (); System.out.println ("Gender:" + gender);//Get annotation properties metaannotation meta = annotation.metaannotation (); System.out.println (Meta.birthday ());}}}

  

Java Annotations Detailed

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.