My understanding of Java (i)--annotations are labeled

Source: Internet
Author: User

In real life, labeling is a ubiquitous phenomenon. Go to the supermarket, go to the mall, each or every kind of item will have its label, even in our own body will also have tags, such as the program Ape, tease, single dog, 80/90, cock silk ... Oh, too much. Sometimes, we also tease friends and colleagues, to put a label for them amused. But this is the point of the note, I would like to say that why I understand the annotation is labeled, although sometimes called it "pinning labels".

Meta Annotations

in Java, four meta annotations are provided, and meta-annotations are annotations. They are:

1[email protected],2[email protected],3[email protected],[email protected]

At the time of our birth, we have been labeled, our household registration according to geographical division, will be affixed to Henan, Hebei, Shandong, Shanxi, Hunan, Hubei and so on 23 provinces and four municipalities in one. In addition, in our life process will also experience the change of the label, children, minors, adults, husbands, wives, fathers, mothers, grandparents and so on. The state will also post us the most common label "citizen" as well as our inherited identity, peasant or city dweller. Why do you say this, because the four meta-annotations provided in Java have something in common with what is mentioned.

@Target

The @Target illustrates the scope of the annotation adornments, as if we were geographically divided, and there are packages, interfaces, classes, enumerations, properties, methods, constructors, and so on in Java. So to show the difference, the annotations are written like this:

1, Package @target (Elementtype.package)
2. Interfaces, classes, enumerations, annotations @target (Elementtype.type)
3. Annotated @target (Elementtype.annotation_type)
4. Constructor @target (elementtype.constructor)
5. Local variable @target (elementtype.local_variable)
6. Method @target (Elementtype.method)
7, the method parameter @target (elementtype.parameter)

@Retention

@Retention represents the life cycle of the annotation. In the course of life we will change the label as time changes, then our label itself shows that it has a certain life cycle, when we are less than 18 years old when called minors, when we are 18 years of age is called an adult, such as white hair, walking can not move is called the elderly, And some tags will accompany a lifetime, such as a man or a woman. In Java, annotations also have its life cycle, from source code to compiled class files, to the runtime after the JDK is loaded. @Retention specifies what the life cycle of the annotations it wants to annotate is, and how long it will be there. The two most common annotations @suppresswarnings and @override in Java, they only exist in the source code. Here is the value of the @retention:

1. Keep @retention (retentionpolicy.source) in source code
2. Keep @retention (retentionpolicy.class) in CLASS file
3. Keep @retention (Retentionpolicy.runtime) at run time

The source code for @SuppressWarnings annotations is as follows:

Package Java.lang;import Java.lang.annotation.*;import Java.lang.annotation.elementtype;import static java.lang.annotation.elementtype.*; @Target ({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, local_variable}) @Retention (retentionpolicy.source) public @interface suppresswarnings {    string[] value ();}

@Documented

By default, Javadoc does not include annotation information, but when a note is labeled with a @documented tag, when a class or method is used to affix the annotation to the @documented label, Javadoc will also include the annotation information in the generated document. This note does not over-interpret, if interested can be found on the Internet to find relevant information.

@Inherited

@Inherited annotations mainly describe an inheritance, meaning that subclasses can inherit this annotation from the parent class (note: The sub-class is only able to get this annotation if the annotation labeled with the @inherited tag is used on the class). As mentioned before, if the parents are rural hukou, then their children will default to the rural hukou. @qualifier annotations in spring, the code is as follows:

Package Org.springframework.beans.factory.annotation;import Java.lang.annotation.documented;import Java.lang.annotation.elementtype;import Java.lang.annotation.inherited;import java.lang.annotation.Retention; Import Java.lang.annotation.retentionpolicy;import Java.lang.annotation.Target; Elementtype.field, Elementtype.method, Elementtype.parameter, Elementtype.type, elementtype.annotation_type}) @ Retention (retentionpolicy.runtime) @Inherited @documentedpublic @interface Qualifier {String value () Default "";}

@Qualifier annotations can be used in fields, methods, method parameters, classes, interfaces, annotations, enumerations, but only when @qualifier is used on a class to be inherited by its subclasses, subclasses can get to this annotation.

Custom Annotations

In addition to some of the tags we were born with accidentally, we in our daily life, whether active or passive, will take the initiative to label others and be labeled by others. When we are in the company, according to the function of the division, will be affixed to a different job label, easy to arrange work, late, leave early, attendance all these labels are used for attendance, excellent staff, technical personnel, management elites and other labels used to set the benchmark, help to improve the enthusiasm and centripetal force. Then these tags are created to be of no use, for the company is naturally a useful place. But, to tease this label is of no use to the company, I think, unless the company is willing to make a tease Force award for staff to be a little useful, otherwise who cares! Labeling a label most of the time will not affect the normal life, in addition to individuals or organizations concerned about the label of your body will have an impact, like now many people see the Henan people three words to open scold the same .... In fact, this is to show that the annotations do not affect the normal operation of the program, there is or does not affect anything, only the program that is concerned about these annotations obtained and resolved the annotations to be processed before changing the behavior of the program itself.

We know that many places in Java's JDK are annotated, and when we use spring, annotations are used more extensively, and spring uses annotations to classify, register, inject, and manage beans, These are the things that spring uses to retrieve the bean's annotation information through reflection when scanning the bean, and to complete the automatic assembly of the bean, and then manage it, providing us with a variety of functions. Here is an example of using reflection to handle custom annotations, and this example is to simply generate a table statement with the following code:

1. Create @table annotations

Package Person.lb.annotation;import Java.lang.annotation.elementtype;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import java.lang.annotation.target;/** * Table name * @author nobounds * * */@Target ({ Elementtype.type}) @Retention (retentionpolicy.runtime) public @interface Table {String value () Default "";}

2. Create @column Annotations:

Package Person.lb.annotation;import Java.lang.annotation.elementtype;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import java.lang.annotation.target;/** * field * @author nobounds * */@Target ( Elementtype.field) @Retention (retentionpolicy.runtime) public @interface Column {String name () default ""; String dataType () default "varchar (20)"; String comment () default "";}

3. Create entity class users:

Package person.lb.annotation: @Table ("Users") public class Users {@Column (name= "ID", datatype= "int") private int id;@ Column (comment= "user name") private string UserName; @Column (name= "pwd", comment= "password") private string password; @Column ( datatype= "varchar", comment= "Mailbox") private string Email;public string GetUserName () {return userName;} public void Setusername (String userName) {this.username = UserName;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;} Public String Getemail () {return email;} public void Setemail (String email) {this.email = email;}}

4. Create Note Processor Annotationhandler:

Package Person.lb.annotation;import Java.lang.annotation.annotation;import Java.lang.reflect.field;public class Annotationhandler {public static void main (string[] args) {StringBuilder sql = new StringBuilder ("CREATE TABLE"); try {Cla SS Clazz = Class.forName ("person.lb.annotation.Users");//Get table annotations on the Users class table tableannotation = (table) Clazz.getannotation (Table.class);//Gets the table name string tableName = Tableannotation.value (). toUpperCase (); if ("" ". Equals ( TableName)) {tableName = Clazz.getname (). toUpperCase (); Sql.append (TableName); Sql.append ("(\ n");//Gets all fields in the class field[] field = Clazz.getdeclaredfields (); For field field: Fields) {//Get all annotations on the field annotation[] fieldannotations = Field.getannotations (); if (Fieldannotations.length > 0) {// Traverse annotations for (Annotation fieldannotation:fieldannotations) {///if @field annotations, then process if (fieldannotation instanceof Column) {// Gets the field name string ColumnName = ((Column) fieldannotation). Name (). toUpperCase (); if ("". Equals (ColumnName)) {columnName = Field.getname (). toUpperCase ();} Get DataType string dataType = ((column) fieldannotation). DataType (). toUpperCase ();//Get comment string comment = ((column) fieldannotation). Comment (), if ("". Equals (comment)) {sql.append (columnName + "\ T" + DataType + ", \ n");} else {sql.append (columnName + "\ T" + DataType + "COMMENT" "+ COMMENT +" ', \ n ');}}}} Sql.append (")"); SYSTEM.OUT.PRINTLN ("Generated SQL statement is: \ n" + sql.tostring ());} catch (ClassNotFoundException e) {e.printstacktrace ();}}}

The above is a simple example of SQL generation, ignoring some non-null judgments in the example, the logic is not rigorous and is used only as a reference. If you feel that there is a problem please leave a message!

My understanding of Java (i)--annotations are labeled

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.