Some important functions of JAVA annotations and how to use them

Source: Internet
Author: User

Java annotations, from the name, are comments, explanations. But the function is not simply a comment. Annotations (Annotation) provide a formalized way for us to add information to our code, which we can use at a later time (by parsing annotations to use the data), with the following common functions:1. Generate the document. This is the most common, and also the earliest annotations that Java provides. Commonly used have @see @param @return and so on;2. Tracking code dependencies, implementing alternative profile features. The most common is the annotation-based configuration that starts with spring 2.5. The function is to reduce the configuration. Now the framework basically uses this configuration to reduce the number of configuration files; 3. Format check at compile time. such as @override before the method, if you do not overwrite the method of the super-class method, the compile time can be checked out;  The package java.lang.annotation contains all the original annotations and interfaces needed to define the custom annotations. such as interface Java.lang.annotation.Annotation is an interface that is inherited by all annotations, and is automatically inherited, does not need to be specified when defined, like all classes automatically inherit object.  The package also defines four meta annotations, documented,inherited,target(Scope, method, properties, construction method, etc.), Retention(life span, source code, class, Runtime). The following will explain their role and how to use them in the example.  inherited: When you define annotations and make them available for program code, annotations in the parent category of the preset are not inherited into subcategories, and you can add java.lang.annotation.Inherited-qualified annotation when defining annotations. This allows you to define the type of annotation to be inherited. Note that annotation inheritance is only valid for class-level annotations (this recommendation is reviewed after reading the full text). More useless, the following step by step from scratch to build our own annotations.   Create the first annotationPackage com.tmser.annotation;Public @interface TestA {//define an empty annotation here, what can it do? I don't know, but he can use it. }  use it in the following program: Package com.tmser.annotation; import Java.util.HashMap;import Java.util.Map; @TestA//Use of class annotationsPublic class Userannotation {    @TestA//Use of class member annotationsprivate Integer age;    @TestA//Use of construction method annotationsPublic userannotation () {            }@TestA//Use of class method annotationsPublic Void A () {@TestA//use of local variable annotationsMap m = new HashMap (0);    }    Public void B (@TestA Integer a) {//using method parameter annotations            }}compile without error, OK, an annotation experiment completed. This annotation is too simple, as if any information can not be passed. Don't worry. Here is a step-by-step refinement, and the four-bit annotation begins in turn. The four meta-annotations are: @Target, @Retention, @Documented, @Inherited, again emphasizing that the following meta annotations are provided by the Java API and are specifically used to define annotations, with the following functions:@Target indicates where the annotation is used, and the possible values are in the enumeration class Elemenettype, including:Elemenettype.constructor----------------------------Constructor Declarationelemenettype.field--------------------------------------domain declarations (including enum instances)elemenettype.local_variable-------------------------local variable declarationsElemenettype.method----------------------------------Method declarationelemenettype.package---------------------------------Package Declarationelemenettype.parameter------------------------------Parameter declarationElemenettype.type---------------------------------------classes, interfaces (including annotation types) or enum declarations           @Retention indicates at what level the annotation information is saved. The optional parameter values are in the enumeration type Retentionpolicy, including:Retentionpolicy.source---------------------------------Annotations will be discarded by the compilerretentionpolicy.class-----------------------------------annotations are available in the CLASS file, but are discarded by the VMThe retentionpolicy.runtime VM-------will also retain annotations at run time, so you can read the information of the annotations through the reflection mechanism.            @Documented include this annotation in Javadoc, which means that this annotation is extracted as a document by the Javadoc tool. The content in the Doc document differs depending on the content of the information for this annotation. Quite with @see, @param and so on.        @Inherited allow subclasses to inherit annotations from the parent class.  learning the most taboo, the most important or hands-on practice, we will be one to experiment.  First:@Target, try to add meta annotations to the annotations we wrote earlier. Package com.tmser.annotation; import Java.lang.annotation.ElementType;import Java.lang.annotation.Target; @Target (Elementtype.package)//In a different place than the previously defined annotations, the meta-annotation Target is used herePublic @interface TestA { }Ctrl + S Save, today's computer comparison to force, our test class there immediately appeared a bunch of errors, in addition to class annotations. I think of this, smart you immediately understand the meaning of this meta-annotation. Is it not for granted that you stole the lazy.? Is there an accident? Careful friend should find out, our test class less a property useless, is elemenettype.package. After we add this attribute to our annotations, we test the meta-annotations of the program all killed, no, there is one not added, good Plus. Package packages, like of course, are loaded in front of the pack. That@TestA package com.tmser.annotation; what also error. This does not understand, do not add to where to add. I do not know, but this is a compilation error, our eclipse will be wrong to us point out that isPackage annotations must is in file Package-info.java, E Although not good, but this simple still difficult to pour several people, the package annotations must be defined in the Package-info.java. Package-info is something, okay. In order to save your time to help you Baidu good (in another one of my other blog post, I find it, ka ka). OK, the target meta annotations are all done.Second meta Note: @Retention parameter retentionpolicy. With the previous experience, this annotation is much simpler to understand, and fortunately there is no special attribute value for this annotation. How to use it under a simple demo:Package com.tmser.annotation; import Java.lang.annotation.ElementType;import Java.lang.annotation.Target; @Target (elementtype.package)@Retention (retentionpolicy.runtime) Public @interface TestA { }the third and fourth meta-annotations are no longer an example. Relatively simple, there is no value, I believe that read the above explanation is clear. Below we continue to explore the use of annotations in depth. The above examples are very simple, and the annotations are not even properties. OK, let's define a property-aware annotation and get the values defined in the annotations in the example program.  before you begin, define the rules for the properties: @interface is used to declare an annotation, in which each method actually declares a configuration parameter. The name of the method is the name of the parameter, and the return value type is the type of the parameter (the return value type can only be base type, Class, String, enum). You can declare the default value of a parameter through default.  Code: @Target ({type,method,field,constructor})@Retention (retentionpolicy.runtime)Public @interface TestA {String name ();int ID () default 0;Class gid ();} Let's change our test class below:Package com.tmser.annotation; import Java.util.HashMap;import Java.util.Map;  @TestA (name= "type", Gid=long.class)//class member annotationsPublic class Userannotation {@TestA (name= "param", Id=1,gid=long.class)//class member annotationsprivate Integer age;@TestA (name= "construct", Id=2,gid=long.class)//construction method AnnotationsPublic userannotation () {}@TestA (name= "public method", Id=3,gid=long.class)//class method annotationPublic Void A () {Map m = new HashMap (0);}@TestA (name= "protected method", Id=4,gid=long.class)//class notationprotected void B () {Map m = new HashMap (0);}@TestA (name= "Private Method", Id=5,gid=long.class)//class method annotationprivate void C () {Map m = new HashMap (0);}Public void B (Integer a) {}} The next most important step is how to read the annotations that we define in the class. As long as the read out of the use of the word is simple. Package com.tmser.annotation; import java.lang.annotation.Annotation;import Java.lang.reflect.Constructor;import Java.lang.reflect.Method; Public class Parseannotation { Public static void Parsetypeannotation () throws ClassNotFoundException {Class clazz = Class.forName ("com.tmser.annotation.UserAnnotation");        annotation[] annotations = clazz.getannotations (); For (Annotation annotation:annotations) {TestA TestA = (TestA) annotation;System.out.println ("id=" "+testa.id () +" "; Name= "" +testa.name () + "";  GID = "+testa.gid ())";         }      }  Public static void Parsemethodannotation () {method[] methods = UserAnnotation.class.getDeclaredMethods (); For (Method method:methods) {             Boolean hasannotation = Method.isannotationpresent (Testa.class); if (hasannotation) {                 TestA annotation = method.getannotation (Testa.class); System.out.println ("method =" + Method.getname ()                        + " ; id = "+ annotation.id () +"; Description = "+ annotation.name () + ";  Gid= "+annotation.gid ());             }          }  } Public static void Parseconstructannotation () {constructor[] constructors = UserAnnotation.class.getConstructors (); For (Constructor constructor:constructors) {         Boolean hasannotation = Constructor.isannotationpresent (Testa.class); if (hasannotation) {                 TestA annotation = (TestA) constructor.getannotation (Testa.class); System.out.println ("constructor =" + Constructor.getname ()                        + " ; id = "+ annotation.id () +"; Description = "+ annotation.name () + ";  Gid= "+annotation.gid ());             }          }  }Public static void Main (string[] args) throws ClassNotFoundException {parsetypeannotation ();parsemethodannotation ();parseconstructannotation ();}} don't talk First, run: id= "0"; name= "type"; gid = class Java.lang.Long method = c; id = 5; description = Private method; Gid= class Java.lang.Long method = A; id = 3; description = Public method; gid= class Java.lang.Long method = b; id = 4; description = protected method; Gid= class Java.lang.Long constructor = com.tmser.annotation.UserAnnotation; id = 2; description = construct; gid= class Java.lang.LongSee, we define the annotations are complete output, you want to use which, directly take to use it. in order not to let this article open too slowly, I omitted the class attribute annotation, and the parameter annotation parsing. In fact, they are all similar. In addition, I do not cite examples of use. Because I think the good tutorial is to speak in detail at the same time, there will be extensions. If I write it all out, and you just study, that basically won't go to the brain, but copy and paste run it over and over. The last reminder:    1. To use good annotations, you must familiarize yourself with the reflection mechanism of Java, as shown in the above example, the parsing of annotations is entirely dependent on reflection. 2. Do not abuse annotations. Usually we seldom touch and use annotations in the programming process, only design, and do not want to let the design have too many configurations This URL can give you some examples of annotations: http://blog.sina.com.cn/s/blog_7540bf5f0100t3mv.html

Some important functions of JAVA annotations and how to use them

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.