Java Annotations-2

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:

    • Generate the document. This is the most common, and also the earliest annotations that Java provides. Commonly used @see @param @return, etc.
    • 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.
    • A format check is made at compile time. such as @override before the method, if you do not override the method of the superclass method, 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, and is not required to be specified when defined, similar to all classes that automatically inherit object.

The package also defines four meta annotations,documented, inherited,Target(Scope, method, properties, construction method, etc.), Retention(Life range, source code, Class,runtime). The following will explain their role and how to use them in the example.

Build the first note: Testa.java

Package annotation.test;/** * @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 default value of the parameter can be declared using default. * Here you can see meta annotations such as @retention and @target to declare the behavior of the annotations themselves. * @Retention the retention policy used to declare annotations, there are three types of class, runtime, and source, which indicate that annotations are saved in the class file, the JVM runtime, and the source code. * Only when the runtime is declared, it is possible to get the annotation information through the reflection API at run time. * @Target used to declare which types of elements an annotation can be added to, such as type, method, and domain. * You can define an annotation, it will automatically inherit annotation */public @interface TestA {//here defines an empty annotation, what can it do? I don't know, but he can use it. There is a supplement later}

Use it in the following program: Userannotation.java

Package Annotation.test;import Java.util.hashmap;import Java.util.Map; /** * This class is designed to test annotations using * @author tmser */@TestA    //Using class Annotations public class Userannotation {        @TestA//Using class member annotations    private Integer age;
@TestA//Use construction method annotation public userannotation () { }
@TestA//Using the class method annotation public void A () { @TestA//using local variable annotations Map 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 , emphasizing again that the next element annotation is Java API provides annotations that 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 Declaration
Elemenettype.field domain declarations (including enum instances)
Elemenettype.local_variable local variable declaration
Elemenettype.method Method declaration
Elemenettype.package Package Declaration
Elemenettype.parameter parameter declaration
Elemenettype.type class, interface (including annotation type) or enum declaration

@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 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.

@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: When you define annotations and use them on program code, annotations in the parent category of the preset are not inherited into subcategories, and you can add java.lang.annotation.Inherited when defining annotations qualified annotation, which allows you to define the annotation type 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.

Study the most taboo, we will one to experiment. First :@Target, try to add meta annotations to the annotations we wrote earlier.

Modify the annotation class: Testa.java

Package annotation.test; Import Java.lang.annotation.elementtype;import java.lang.annotation.target;/*  * Define annotation Test  * First Use Elementtype.type */@Target (elementtype.package) public  @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 annotation.test;

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 is

Package 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 what thing, good to save your time to help you Baidu good, transmission door. 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: Testa.java

Package Annotation.test;import Java.lang.annotation.elementtype;import java.lang.annotation.target;/*  * Define Annotations Test  * First uses the Elementtype.type * Run level as the runtime, so that later test parsing */@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.

Testa.java

Package Annotation.test;import Java.lang.annotation.elementtype;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import java.lang.annotation.target;/** * Define annotations Test <br> * for easy testing: annotation target is a class method, Properties and Construction Methods <br>  * Annotations contain three element IDs, name and GID;  <br> * ID element has default value of 0 <br> */@Target ({Elementtype.type,elementtype.method,elementtype.field, Elementtype.constructor}) @Retention (retentionpolicy.runtime) public @interface TestA {    String name ();    int ID () default 0;    Class<long> gid ();}

The following changes our test class: Userannotation.java

 1 package annotation.test; 2 3 Import Java.util.HashMap; 4 Import Java.util.Map; 7/** 8 * This class is specifically used to test annotations using 9 */10 @TestA (name= "type", Gid=long.class) 12//Using class Annotations public class Userannotation {16 @ TestA (name= "param", id=1,gid=long.class)//Using class member annotations, the private Integer age;18 @TestA (name= "construct", id=2,gid=l Ong.class)//using the construction Method annotated public userannotation () {}23 @TestA (name= "public method", id=3, Gid=long.class)      The public method is used to annotate public void A () {map<string, string> m = new hashmap<string, string> (0); 27         }28 @TestA (name= "protected method", id=4, Gid=long.class)//protected methods annotated protected void B () {31  Map<string, string> m = new hashmap<string, string> (0),}33 @TestA (name= "Private Method", id = 5, gid=long.class)//Private method note + private void C () {map<string, string> m = new Hashmap<st Ring, string> (0); PNs}38, public void B (Integer A) {41}42} 

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 Annotation.test;import Java.lang.annotation.annotation;import Java.lang.reflect.constructor;import Java.lang.reflect.field;import Java.lang.reflect.method;public class Parseannotation {/** * Simple print out Userannotation class Class Annotations Used * This method only prints annotations of type types * @throws classnotfoundexception */public static void Parsetypeannotation ()        Throws classnotfoundexception{Class clazz = Class.forName ("annotation.test.UserAnnotation");        annotation[] annotations = clazz.getannotations ();            for (Annotation annotation:annotations) {TestA TestA = (TestA) Annotation;  System.out.println ("type name =" +clazz.getname () + "|  id = "+ testa.id () +" |                      Name = "+ testa.name () +" |        GID = "+ testa.gid ());     }}/** * Simply print out the method annotations used in the Userannotation class * This method only prints annotations of type method * @throws classnotfoundexception */public static void Parsemethodannotation () throws classnotfoundexception{MetHod[] methods = UserAnnotation.class.getDeclaredMethods (); For (method Method:methods) {/* * Determine whether there are annotations of the specified annotation type in the method */Boolean HasAn            notation = method.isannotationpresent (Testa.class);                if (hasannotation) {TestA annotation = method.getannotation (Testa.class);  System.out.println ("Method name =" + method.getname () + "|  id = "+ annotation.id () +" |  Description = "+ annotation.name () +" |            GID = "+ annotation.gid ()); }}}/** * Simply print out the construction method used in the Userannotation class Note * This method only prints annotations of the construction method type * @throws Classnotfoundexc Eption */public static void Parseconstructannotation () throws classnotfoundexception{constructor[] Constr        Uctors = UserAnnotation.class.getConstructors ();              for (Constructor constructor:constructors) {/* * Determine if there are annotations of the specified annotation type in the construction method */ Boolean HasannotatIon = Constructor.isannotationpresent (Testa.class); if (hasannotation) {/* * Returns the specified type of method based on the annotation type annotation */TestA Annota                tion = (TestA) constructor.getannotation (Testa.class);   System.out.println ("constructor =" + constructor.getname () + "|  id = "+ annotation.id () +" |   Description = "+ annotation.name () +" |            Gid= "+annotation.gid ()); }}}/** * Simply print out the field annotations used in the Userannotation class * This method only prints annotations of method type * @throws Classnotfoundexc Eption */public static void Parsefieldannotation () throws classnotfoundexception{field[] fields = Useranno        Tation.class.getDeclaredFields ();            for (Field Field:fields) {Boolean hasannotation = Field.isannotationpresent (Testa.class);                if (hasannotation) {TestA annotation = field.getannotation (Testa.class); System.oUt.println ("Field =" + field.getname () + "|  id = "+ annotation.id () +" |  Description = "+ annotation.name () +" |            Gid= "+annotation.gid ()); }}} public static void Main (string[] args) throws ClassNotFoundException {System. out. println ("------------------------------Parsing type Annotations----------------------------------------------------------");        Parsetypeannotation (); System. out. println ("------------------------------Analytic Method Annotated-------------------------------------------------------");        Parsemethodannotation (); System. out. println ("------------------------------Analytic Construction Method (Construct) Annotated------------------------------------------");        Parseconstructannotation (); System.out.println ("------------------------------Parse Field"        Annotated-----------------------------------------------------");    Parsefieldannotation (); }}

Don't talk first, run:

The

------------------------------parse the type annotation----------------------------------------------------------
Type name = annotation.test.UserAnnotation | id = 0 | name = Type | gid = Class Java.lang.Long
-------------------- ----------parsing method Annotations-------------------------------------------------------
Method name = c | id = 5 | description = P Rivate Method | GID = Class Java.lang.Long
Method name = a | id = 3 | description = Public Method | gid = Class Java.lang.Long
Metho D name = B | id = 4 | Description = protected Method | GID = Class Java.lang.Long
------------------------------Analytic construction Method (Construct) Annotation------------------------------------------
Constructor = annotation.test.UserAnnotation | id = 2 | description = Construct | Gid= class Java.lang.Long
------------------------------parse field Annotation-----------------------------------------------------
Field = age | id = 1 | description = param | gid= class java.la Ng. Long

See, 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 parsing of parameter annotations. 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.

most after mention Awake below :

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 make the design too much configuration.

Java Annotations-2

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.