Java Annotations Programming Guide

Source: Internet
Author: User

Java Annotations Programming Guide Java Annotation Tutorial+1 concept annotations are a new feature of the Java language introduced by JDK1.5. Annotations are similar to interfaces, which are at the same level as classes, interfaces, and enumerations, which are called as a type of java. +1The 1Java Language guide explains annotations (also known as metadata), providing us with descriptive information about the program code that is not part of the program itself. Annotations do not directly affect the work of their commented code. +12Java Programming Ideas explaining annotations (also known as metadata) provides a formalized way for us to add information to our code so that we can use the data very conveniently at some point later. +1the. 3Java Language Specification Explanatory note is a containing annotation type and 0 or more keys-the Java modifier of the value pair. Each of these keys-value pairs are bound to a different annotation type value. The object of the annotation is simply the programming element that binds the information to its callout. +2 Purpose The use of annotations includes (but is not limited to) the following: Provides information for compilers: annotations can be used by compilers (such as Eclipse, IntelliJ) to detect errors and known warnings, such as Java built-in @deprecated, @ The override and @suppresswarnnings are often used. Compile-time and deploy-time attach operations: Software tools can generate executable code, XML files, and so on, from the annotations information at compile time or during deployment. If you generate a description document, Jax-ws,jax-RS uses annotations to generate the XML file for the service description. Runtime actions: Some annotations can be interpreted when the program is running. The following hibernate and Ibatis use it for dynamic table structure and SQL statement generation, etc. junit uses annotations to streamline test code and processes from the 4.x release ASPECTJ use annotations to provide non-intrusive, tangent-oriented programming spring also uses annotations to make XML configuration management a mate or alternative some tools are based on Annotations such as code analysis, and so on, can really help us reduce, beautify, or add extra functionality to existing code. +3 principle the annotations mentioned at the beginning of the article are the same type as the class and interface. The annotation handler obtains the annotations in the program code through the Java reflector, then resolves and processes the relevant annotations according to the pre-set processing rules to achieve the function target set by the host itself. +4 Syntax+4.1 defining the definition of annotations is similar to the definition of an interface and is somewhat different. The following is a definition example1. No parameter Annotations/**java.lang.Deprecated Source Code*/@Documented//include this note in the Javadoc@Retention (Retentionpolicy.runtime)//the VM Runtime retains the note, which can be obtained through reflection. @Target (Value={constructor, FIELD, local_variable, METHOD, Package, PARAMETER, TYPE})//The target to which this annotation applies (construction method, field, local variable, method, package, parameter, type) Public@InterfaceDeprecated {//"Deprecated" is the annotation name//annotations are declared using @interface}  2. Annotations with Parameters@Target ({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, local_variable}) @Retention (Retentionpolicy.source)//This note remains in the Java original file only Public@Interfacesuppresswarnings {/**supported parameter list all,deprecation,unchecked,fallthrough,path,serial,finally, etc.*/string[] Value ();//This annotation can accept an array of argumentssee here for more parameters that are acceptable for this annotation. 3. Custom Annotations/****************************************************************************** * This software is under the Apache License Version 2.0 * author:tao-mail:[email protected] * Spreading Your Heart ************************************ ****************************************  */     Packageatao.annotation; Importjava.lang.annotation.Documented; ImportJava.lang.annotation.ElementType; Importjava.lang.annotation.Retention; ImportJava.lang.annotation.RetentionPolicy; ImportJava.lang.annotation.Target; /*** A simple test case annotation with two parameters, this annotation only applies to "methods". *   * @author<a href= "Mailto:[email protected]" >Tao</a> *@since1.0*/@Documented @Target (elementtype.method) @Retention (retentionpolicy.runtime) Public@InterfaceUseCase {/**test Case Number*/       Public intID (); /**Test Case Description*/       PublicString description ()default"No description"; }  4. The simplest annotations@Interfacenaked{}5. Allow subclasses to inherit annotations from parent classes/**allow subclasses to inherit annotations from parent classes*/@Inherited Public@Interfacetrustfather{} Summary, annotation definition includes: Subject declaration, permission modifier+ @Interface+Note name annotation description applicable target: @Target retention level: @Retention whether to produce Javadoc: @Documented allow subclasses to inherit annotations from the parent class: @Inherited Other annotation annotations contain field settings (Example 2, 3)+4. 2 Using/****************************************************************************** * This software is under the Apache License Version 2.0 * author:tao-mail:[email protected] * Spreading Your Heart ************************************ ****************************************  */     Packageatao.annotation; Importjava.util.ArrayList; Importjava.util.List; /*** One using the note password Tool class * *@author<a href= "Mailto:[email protected]" >Tao</a> *@since1.0*/   Public classpasswordutils {@UseCase (id= Description = "Password must contain at least one number")       Public BooleanValidatePassword (String password) {return(Password.matches ("\\w*\\d\\w*")); } @UseCase (ID= 48)       Publicstring Encryptpassword (string password) {return NewStringBuilder (password). reverse (). toString (); } @UseCase (ID= Description = "The new password cannot be duplicated with the password that was used")       Public BooleanCheckfornewpassword (List <String>prevpasswords, String password) {          return!prevpasswords.contains (password); }            /**@deprecatedThe landlord decided not to recommend the use of this method, their own casually find all the others try it.*/@Deprecated Public voidDeprecatedmethod () {} @SuppressWarnings ({"Unused", "rawtypes" })       Public voidUnsafemethod () {//@SuppressWarnings ({"Unused", "Rawtypes"})//This can still be used here, because this annotation supports types such as decorated classes and local variables. List unsafelist =NewArraylist<string>(); }  }  +4. 3 Write a note processor as follows a simple test case processor written out of Java reflection/****************************************************************************** * This software is under the Apache License Version 2.0 * author:tao-mail:[email protected] * Spreading Your Heart ************************************ ****************************************  */     Packageatao.annotation; ImportJava.lang.reflect.Method; Importjava.util.ArrayList; Importjava.util.Collections; Importjava.util.List; /*** Note Processor for use case detection * *@author<a href= "Mailto:[email protected]" >Tao</a> *@since1.0*/   Public classUsecasechecker { Public Static voidTrackusecases (List <Integer> usecases, Class <?>cl) { for(Method m:cl.getdeclaredmethods ()) {UseCase UC= M.getannotation (usecase.class); if(UC! =NULL) {System.out.println ("Find use Case:" + uc.id () + "" +uc.description ()); Usecases.remove (NewInteger (Uc.id ())); }          }           for(inti:usecases) {System.out.println ("Warning-missing use case:" +i); }      }         Public Static voidMain (string[] args) {List<Integer> usecases =NewArrayList <Integer> (); Collections.addall (usecases,1, 2, 3, 4,5); Trackusecases (Usecases, passwordutils.class); }    }  /**run the output as: Find the use case: 1 The password must contain at least one number to find the use case: 4 The new password cannot be used repeatedly to find a use case: 3 No description warning-missing use case: 2 warning-missing use case: 5*/Now that we've gone through a simple Java annotation usage process, let's talk about the language elements of annotations and the associated Java APIs.+5 language elements+5. 1 USD Annotations to Jdk7,java provides 3 built-in standard annotations (@Override, @Deprecate, @SuppressWarnings) and four meta-annotations (@Target, @Retention, @Documented, @ inherited). Careful people will find that these are mentioned in the above narrative. @Target to indicate where the annotation can be used. The available parameters are (constructed method, field, local variable, method, package, parameter, type (class, interface, annotation, enumeration)). It uses the ElementType enumeration parameter, the reader can read the ElementType enumeration production to see the original explanation. @Retention, the life cycle of the annotation is marked with Retentionpolicy enumeration parameters. Consists of three (retentionpolicy.source,retentionpolicy.class,retentionpolicy.runtime). Source,runtime has been explained in addition to the preceding code. As for class, the annotations are saved in the class file and are discarded when the class is loaded. In fact, Java has already used the annotation mechanism extensively in the API of its EE specification, but the file Lookup tool confirms the JDK (J2SE/Java ee) to the end of 1.7 does not provide a reference to the Retentionpolicy.class life cycle annotations. This may also indicate that the definition of the classs life cycle may be a pile of scrap wood. @Documented, which is included in Javadoc @inherited, allows subclasses to inherit annotations from the parent class+5. 2 default parameters when the annotation definition contains only one string parameter, you can use the following method to assign a value to the parameter using the direct string Fill method//definition@Interfacesimpleusecase{string value ();} //Use@SimpleUseCase ("This is so simple, do not use key-value pairs to assign")  +5. 3 naked annotations as shown in the previous example @nacked, the @target (all ElementType types) will be used by default, @Retention (Retentionpolicy.class). See here or Java Retention the explanation in the source code. +5. 4 repeatable annotations Starting from JDK8 Java provides a self-decorated, circular annotation @repeatable that uses this callout adornment to allow the annotations to be used multiple times on the target. Note Download JDK8, the following code to compile. @Repeatable (schedules.class)   Public@InterfaceSchedule {String dayofmonth ();  String DayOfWeek ();  String Hour (); } @Schedule (DayOfMonth= "Last") @Schedule (DayOfWeek= "Fri", hour= "23")   Public voidDoperiodiccleanup () {/**method Body*/ }  +6 Annotation Tools aptapt Full name Annotation processing tool. Note: The associated APIs in APT tools and com.sun.mirror packages have been deprecated since Java SE 7. Use the corresponding option options in the Javac tool and the APIs in the Javax.annotation.processing, Javax.lang.model package. The APT tool is a command-line practical annotation handler. It includes a set of reflection APIs that support common operations for handler annotations (JSR175). These reflection APIs provide a build-time, source-based, read-only view of the program structure. They are designed to assist Java generics in building a type system data model for the Java programming language (JSR 14). First the APT tool runs the annotation handler to generate new source code and other files. Next, Apt prompts the compiler to compile the original and generated source files. This approach will make the development cycle simpler. JSR269, also known as the Language model API, has two basic parts: the Java programming language Model API and the Write note processor API. This feature can be used with the JAVAC command new option; JSR 269 has corresponding support instructions, and Javac now replaces the APT tool in JDK5. The following is the package that contains the relevant API: Javax.annotation.processingjavax.lang.modeljavax.lang.model.elementjavax.lang.model.typejavax.lang.model.uti I will use another article to describe the usage of the annotation tool separately. Because of the reason of space, it is no longer in depth. Interested readers can read the Java APT Getting Started directly.+7 References Java Programming Ideas Fourth Edition 20th chapter Java Annotations Tutorial from Oracle Jenkov java Annotation tutorialspring annotationswhat -is-the-list-of-valid-suppresswarnings-warning-names-in-Javajava7Aptjava Language Specification7Java APT Getting started.http://blog.csdn.net/river_like/article/details/21542669

Java Annotations Programming Guide

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.