Java using annotation annotations-(i)

Source: Internet
Author: User

It's been almost 4 years since we've been using Java and it's time to leave something behind. Today in the realistic body class Pojo feel has been writing the annotations that have been using MyBatis spring annotations today look at how the source code is defined. You can follow my Sina Weibo: Crazy Yang Zhengren

The first thing to do is to study annotations I only remember annotation and basic usage public @interface ****{}

Found some information on the Internet to see the above definition @documented description is this is the note and then in the @documented this note below we see

@Documented @retention (retentionpolicy.runtime) @Target (elementtype.annotation_type) public @interface documented {}

Look, basically, that means

@Retention (Retentionpolicy.runtime) is the time to run

@Target (Elementtype.annotation_type) The meaning of this annotation is to run above the type above.

Then we'll use the 3 annotations above the original note to mimic hibernate to write a

Define a table to annotate its own amount

First define an enumeration of a database type

public enum Dbenum {//Define Database enumeration May 17, 2015 22:41:47mysql, ORACLE, MSSQL, DB2, SYBASE}

Then define a table annotation

@Target (Elementtype.type) @Retention (retentionpolicy.runtime) @Documentedpublic @interface Table {public String value () Default ""; Use the name of the table//Define Database Enumeration public Dbenum type () default dbenum.mssql; Use MySQL database by default}

Define the column annotations below

@Target (Elementtype.field) @Retention (retentionpolicy.runtime) @Documentedpublic @interface Column {// The name of the column that uses the database public String value () default ""; Use '} by default

A table must have some and ID at the time of the save must be added an ID note

@Target (Elementtype.field) @Retention (retentionpolicy.runtime) @Documentedpublic @interface ID {//Use ID annotation above the column Description This column is the ID column when you do save the policy to use your own increased May 17, 2015 22:44:43public boolean unique () default false; Use a unique constraint May 17, 2015 22:46:43}

The annotations are defined well then we're going to write an entity class that's Pojo

public class user {@ID @columnprivate int userid; @Columnprivate  String  Username, @Columnprivate  String password; @Columnprivate  String createtime; @Columnprivate  String updatetime; @Columnprivate  String telephone; @Columnprivate  int status;@ columnprivate string nickname; @Columnprivate  int integral;public int getuserid ()  {return userid;} Public void setuserid (Int userid)  {this.userid = userid;} 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 getcreatetime ()  {return createtime;} Public void setcreatetime (string createtime)  {this.createtime = createtime;} Public string getupdatetime ()  {return updatetime;} Public void setupdatetime (String updatetime)  {this.updatetime = updatetime;} Public string gettelephone ()  {return telephone;} Public void settelephone (String telephone)  {this.telephone = telephone;} Public int getstatus ()  {return status;} Public void setstatus (Int status)  {this.status = status;} Public string getnickname ()  {return nickname;} Public void setnickname (String nickname)  {this.nickname = nickname;} Public int getintegral ()  {return integral;} Public void setintegral (int integral)  {this.integral = integral;}}

Remember to add the annotations we defined earlier


Below we can parse this note directly on the code bar there is no understanding of what can be commented on the amount below

public class aplasmain {//  test method  2015 May 17 22:32:23public static void  Main (String[] args)  throws Exception {//  define a user type   reflect all fields below this type map<string,  Object> map = new HashMap<String, Object> (); Class<? extends object> clazz = user.class;map.put ("ClassName",  Clazz.getsimplename ()); Map.put ("TableName",  clazz.getsimplename ());//  judgment   If the type uses table annotations if  (Clazz.isannotationpresent (Table.class))  {table table = clazz.getannotation (Table.class); if  (Table!=null && !table.value (). Equals (")")  { //  default setting is "" "  So directly judge whether is "" Can Map.put ("TableName",  table.value ());}} Take out all the fields below this type Field[] fields = clazz.getdeclaredfields ();//  judge the fields below List<map<string,  Object>> mapList = new ArrayList<Map<String,Object>> ();for (Field field : fields)  {Map<String, Object> fieldMap = new  Hashmap<string, object> (); Fieldmap.put ("Property",  field.getname ()); Fieldmap.put ("column",  field.getname ()); Fieldmap.put ("unique",  false);//  Determines whether column annotations are used if  ( Field.isannotationpresent (Column.class))  {column column = field.getannotation (Column.class );if  (Column!=null && !column.value (). Equals (""))  {fieldmap.put ("column",  Column.value ());}}   Determine whether to use ID annotations if  (Field.isannotationpresent (id.class))  {ID id =  Field.getannotation (Id.class);if  (Id!=null && !id.unique ())  {fieldMap.put ("unique" ,  true);}}   Finally put this in the list below Maplist.add (FIELDMAP);} Map.put ("list",  maplist);//  Print to JSON   see results System.out.println (Jsonarray.fromobject (map));}}

Finally look at the result of the output  

[    {         "TableName":  "User",          "List": [             {                  "Unique": true,                  "column":  "userid",                  "Property":  "userid"              },            {                  "Unique": false,                  "column":  " Username ",                  "Property":  "username"              },             {                  "Unique": false,                  "column":  "password",                  "Property":  "Password"              },             {                 "unique":  false,                 " Column ": " Createtime ", &NBsp;                "Property":  "Createtime"             },             {                  "Unique": false,                  "column":  "UpdateTime",                  "Property":  "UpdateTime"              },             {                  "Unique": false,                  "ColuMN ": " Telephone ",                  "Property":  "Telephone"              },            {                  "Unique": false,                  "column":  "status",                  "Property":   "Status"             },             {                  "Unique": false,                  "column":  "nickname",                  "Property":  "nickname"              },            {                  "unique":  false,                  "column":   "Integral",                  "Property":  "integral" &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;}         ],         "ClassName":   "User" &NBSP;&NBSP;&NBSP;&NBSP;}]

It's what we want. The results show that the parsing is right.

The following article explains the principles of annotation. Thank you for your attention

Java using annotation annotations-(i)

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.