Java annotation programming guide

Source: Internet
Author: User

Java annotation programming guide
Java Annotation Tutorial

+ 1 concept annotation is a new Java language feature introduced by JDK1.5. Annotations are very similar to interfaces. They are at the same level as classes, interfaces, and enumeration. They are all called java types ). + 1.1Java

Annotation (also called metadata) provides the description of the program code, which does not belong to the program itself. Annotations are not direct

It affects the work of the annotated code.

+ 1.2Java programming ideology explanation

Annotations (also called metadata) provide a formal method for us to add information to code, so that we can easily add information at a certain time later.

.

+ 1.3Java

Annotation is a Java modifier that contains annotation types and zero or multiple key-value pairs. Each key-value pair is bound with a different annotation type value. Annotated

Simply put, the goal is to bind information to the programming elements marked by it.

+ 2 usage

Annotations are used as follows (but are not limited:

    Provide information for the compiler: Annotations can be used by the compiler (such as Eclipse and IntelliJ) to detect errors and known warnings, such as @ Deprecated, @ Override, and @ SuppressWarnnings built in Java.
      Additional operations during compilation and deployment: software tools can generate executable code and XML files based on annotation information during compilation or deployment. For example, to generate a description document, Jax-ws and Jax-rs generate an XML file of the service description using annotations.
        Runtime operations: Some Annotations can be explained again when the program is running. The following Hibernate and Ibatis use it for dynamic table structure and SQL statement generation operations such as Junit from 4. in Version x, annotations are used to simplify test code and procedures. AspectJ uses annotations to provide non-intrusive Aspect-Oriented Programming. Spring also uses annotations for XML configuration management. annotations for code analysis and so on can often help us reduce and beautify code, or add additional functions for existing code.

        + 3 Principle

        The annotation and class and interface mentioned at the beginning of the article are the same type. The annotation handler obtains the annotation in the program code through the Java reflection machine, and then parses and processes the annotation according to the preset processing rules to achieve the function goal set by the host itself.

        + 4 syntax + 4.1 Definition

        The annotation definition is similar to the interface definition. The following is a definition example:

        1. No parameter Annotation

        /** Java. lang. deprecated source code */@ incluented // include this annotation in JavaDoc @ Retention (RetentionPolicy. RUNTIME) // The annotation is retained during the vm runtime and can be obtained through reflection. @ Target (value = {CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE }) // target of this annotation (constructor, field, local variable, method, package, parameter, type) public @ interface Deprecated {// "Deprecated" indicates the annotation name // annotation. @ interface declaration is used}
        2. Parameter Annotation

        @ Target ({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE}) @ Retention (RetentionPolicy. SOURCE) // This annotation is only retained in the list of parameters supported by public @ interface SuppressWarnings {/** in the original Java file all, deprecation, unchecked, fallthrough, path, serial, finally and so on */String [] value (); // This annotation can accept a parameter array}
        For more parameters acceptable for this annotation, see here.

        3. Custom Annotation

        /*************************************** **************************************** This software is under the Apache License Version 2.0 * Author: tao-mail: cn.java.river@gmail.com * Spreading Your Heart *********************************** **************************************** **/package atao. annotation; import java. lang. annotation. documented; import java. lang. annotation. elementType; import java. lang. annotation. retention; import java. lang. annotation. retentionPolicy; import java. lang. annotation. target;/*** a simple test case annotation containing two parameters. This annotation is only applicable to "methods ". ** @ author Tao * @ since 1.0 */@ receivented @ Target (ElementType. METHOD) @ Retention (RetentionPolicy. RUNTIME) public @ interface UseCase {/** Test Case No. */public int id ();/** Test Case description */public String description () default "no description ";}
        4. Simplest annotations

        @interface Naked{}
        5. Allow subclass to inherit the annotation of the parent class

        /** Allow subclass to inherit the annotation of the parent class */@ Inheritedpublic @ interface TrustFather {}

        In summary, the annotation definitions include:

        Topic declaration, permission Modifier + @ interface + annotation name annotation description Target: @ Target Retention level: @ Retention whether JavaDoc: @ incluented allows subclass to inherit the annotation of the parent class: @ Inherited other annotation containing field settings (in example 2 and 3) + 4.2

        /*************************************** **************************************** This software is under the Apache License Version 2.0 * Author: tao-mail: cn.java.river@gmail.com * Spreading Your Heart *********************************** **************************************** **/package atao. annotation; import java. util. arrayList; import java. util. list;/*** a password tool class using the above annotation ** @ author Tao * @ since 1.0 */public class PasswordUtils {@ UseCase (id = 47, description = "the password must contain at least one number") public boolean validatePassword (String password) {return (password. matches ("\ w * \ d \ w *");} @ UseCase (id = 48) public String encryptPassword (String password) {return new StringBuilder (password ). reverse (). toString () ;}@ UseCase (id = 49, description = "the new password cannot be the same as the one used") public boolean checkForNewPassword (List
            
             
        PrevPasswords, String password) {return! PrevPasswords. contains (password);}/** @ deprecated the author decided not to recommend this method. Please try it by yourself. * // @ Deprecated public void deprecatedMethod () {}@ SuppressWarnings ({"unused", "rawtypes"}) public void unsafeMethod () {// @ SuppressWarnings ({"unused ", "rawtypes"}) // It can still be used here, because this annotation supports types such as modifier classes and local variables. List unsafeList = new ArrayList
             
              
        ();}}
             
            
        + 4.3 write annotation Processors

        The following is a simple test case processor written based on Java reflection:

        /*************************************** **************************************** This software is under the Apache License Version 2.0 * Author: tao-mail: cn.java.river@gmail.com * Spreading Your Heart *********************************** **************************************** **/package atao. annotation; import java. lang. reflect. method; import java. util. arrayList; import java. util. collections; import java. util. list;/*** annotation processor used for case detection ** @ author Tao * @ since 1.0 */public class UseCaseChecker {public static void trackUseCases (List
            
             
        UseCases, Class
             Cl) {for (Method m: cl. getDeclaredMethods () {UseCase uc = m. getAnnotation (UseCase. class); if (uc! = Null) {System. out. println ("find the use case:" + uc. id () + "" + uc. description (); useCases. remove (new Integer (uc. id () ;}}for (int I: useCases) {System. out. println ("Warning -- missing Use Case:" + I) ;}} public static void main (String [] args) {List
             
              
        UseCases = new ArrayList
              
               
        (); Collections. addAll (useCases, 1, 2, 3, 4, 5); trackUseCases (useCases, PasswordUtils. class) ;}}/** the output result is: Find Use Case: 1. The password must contain at least one number. Find Use Case: 4. The new password cannot be found again with the previous one: 3. No descriptive warning-missing Use Cases: 2. Warning-missing Use Cases: 5 */
              
             
            

        So far, we have completed the process of using a simple Java annotation. Next we will talk about the language elements of the annotation and related Java APIs.

        + 5 language elements + 5.1 yuan Annotation

        To JDK 7, Java provides three built-in standard annotations (@ Override, @ Deprecate, @ SuppressWarnings) and four meta annotations (@ Target, @ Retention, @ incluented, @ Inherited ). Careful people will find that these have been mentioned in the above description.

        @ Target indicates where the annotation is available. Available parameters include (constructor, field, local variable, method, package, parameter, type (class, interface, annotation, enumeration )). With the ElementType enumeration parameter, you can refer to the original interpretation of ElementType enumeration.
        @ Retention: indicates the life cycle of the annotation. It uses the RetentionPolicy enumeration parameter. Contains three (RetentionPolicy. SOURCE, RetentionPolicy. CLASS, RetentionPolicy. RUNTIME ). In addition to the previous code. CLASS indicates that the annotation will be saved in the class file, and the CLASS will be discarded when it is loaded. In fact, Java has widely used the annotation mechanism in its J2EE standard API, but the file search tool confirms JDK (j2se/j2ee) no RetentionPolicy is provided for reference until the end of 1.7. CLASS lifecycle annotation. This may also indicate that the definition of the CLASSS life cycle may be a pile of waste. @ Incluented: Contains @ Inherited in JavaDoc, allowing subclass to inherit the annotation of the parent class

        + 5.2 default parameters

        When the annotation definition only contains one string parameter, you can assign a value to the parameter using the following method:

        // Define @ interface SimpleUseCase {String value ();} // use @ SimpleUseCase ("is that simple, do not use key-value Pair assignment ")
        + 5.3 native annotation @ Nacked in the preceding example, @ Target (all ElementType types) and @ Retention (RetentionPolicy. CLASS ). see here or the explanation in Java Retention source code.
        + 5.4 repeated annotations

        Java has provided a circular annotation @ Repeatable that allows self-modification since JDK8. The annotation definition uses this annotation to allow continuous use of this annotation on the target. Please download JDK8 and compile the following code.

        @ Repeatable (Schedules. class) public @ interface Schedule {String dayOfMonth (); String dayOfWeek (); String hour () ;}@ Schedule (dayOfMonth = "last ") @ Schedule (dayOfWeek = "Fri", hour = "23") public void doPeriodicCleanup () {/** method body */}
        + 6 the Annotation Tool APTAPT stands for Annotation Processing Tool. Note: The APT tool and related APIs in the com. sun. mirror package have been deprecated from Java SE 7. Use the corresponding options in the javac tool and the APIs in the javax. annotation. processing and javax. lang. model packages.

        APT is a command line practical annotation processing program. It includes a set of reflection APIs that support common operations for processing program annotations (JSR 175 ). These reflection APIs provide a program structure based on source code and read-only views during construction. They are designed to help Java generics better construct the type system data model (JSR 14) of the Java programming language ).
        First, the APT tool runs the annotation processing program to generate new source code and other files. Next, APT will prompt the compiler to compile the original and generated source files. This method simplifies the development cycle.

        JSR 269, also known as the language model API, has two basic components: Java programming language model API and annotation processor API. You can use this function using the new option of the javac command. JSR 269 has corresponding support instructions. javac now replaces the APT tool in JDK 5.

        The packages of related APIs are as follows:

        • Javax. annotation. processing
        • Javax. lang. model
        • Javax. lang. model. element
        • Javax. lang. model. type
        • Javax. lang. model. util I will introduce the use of annotation tools in another article. Here, due to space reasons, we will not go into depth. Interested readers can directly read Java APT Getting Started.

          + 7 ReferencesJava programming ideas Chapter 4Java Annotations Tutorial from OracleJenkov Java Annotation TutorialSpring AnnotationsWhat-is-the-list-of-valid-suppresswarnings-warning-names-in-java
          Java 7 APTJava Language specification 7Java APT Getting Started.

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.