Use of Java custom annotations

Source: Internet
Author: User

Recently learned Java custom annotations, finally know the framework of those annotations is why did written out, I can also write their own framework, I define annotations, listen to is not very cow look? Do not heart, act quickly, the code is very simple, together to learn it!

This example is a copy of the framework of the SQL Assembly example, with annotations to the model is the entity class annotation, you can write the query to the field of SQL. Well, don't say a word, the code will know. You can change it according to your needs.

Package Com.annotation.demo;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;/** * 1. @interface define the Annotation keyword * 2.         Meta Annotations: * @Target: Scope of Annotations * ElementType * Type: class Interface declaration * Consturctor: Constructor Method declaration * FILED: Field declaration *     local_variable: Local Variable declaration * Method: Methods declaration * Parckage: Package declaration * Parmeter: parameter declaration * @Retention: Declaration period of Annotations *     Retentionpolicy * Runtime: Runtime exists, can be read by reflection * Source: Only in the source display, compile will be discarded * class: Compile time will be recorded in class, run-time ignored * @Inherited: Allow subclasses to inherit * @Documented: NOTE * 3 is included when generating Javadoc. Use custom annotations * @< annotation name > (< member name 1>=< member value 1>,< member name 2>=< member Value 2>,...) * such as: * @MyAnnotation (name= "Stephen.H Uang ", date=" 2015-7-30 ") * public void MyMethod () {*//todo *} * * * @author Stephen Huang * @see Http://blo g.csdn.net/u010571844 * * */@Target({elementtype.type}) @Retention (retentionpolicy.runtime) @Inherited @documentedpublic @interface Table {/** * 1. Member with no parameter no exception declaration * 2. You can specify a default value for a member with default, such as: int age () default 18; * 3. The member type is restricted, and the legal type includes the original type and the String,class,annotation, Enumeration. * 4. If the annotation has only one member, the member name must be named value (), and the member name and ' = ' can be ignored when used. * 5. Note Classes can have no members, and annotations without members are called callout annotations. * @return */string value ();}
2. Re-define the annotations for the fields in the data table CLOUNM

Package Com.annotation.demo;import Java.lang.annotation.elementtype;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import java.lang.annotation.target;/** *  * @author Stephen Huang * * * * @Target ({Elementtype.field}) @Retention (retentionpolicy.runtime) public @interface Column {String value ();}

3. Define the user entity class

Package Com.annotation.demo, @Table ("User") public class User {@Column ("id")    private Integer ID, @Column ("user_name ")    private string userName; @Column (" email ")    private string email;    Public Integer GetId () {return ID;} public void SetId (Integer id) {this.id = ID;} Public String GetUserName () {return userName;} public void Setusername (String userName) {this.username = UserName;} Public String Getemail () {return email;} public void Setemail (String email) {this.email = email;}}

4. Testing

Package Com.annotation.demo;import java.lang.reflect.field;import java.lang.reflect.method;/** * * @author Stephen Huang * */public class Test {/** * @param args */public static void main (string[] args) {User User1 = new User (); user1.set ID (1);//search User ID 1User user2 = new User (); User2.setusername ("Stephen");//search user name ' stephen ' User User3 = new User (); User3.setemail ("[email protected], [email protected]");//search user email ' String sql1 = query ( User1); String sql2 = query (User2); String sql3 = query (USER3); System.out.println (SQL1); System.out.println (SQL2); System.out.println (SQL3);} private static String query (Object f) {StringBuffer SB = new StringBuffer ();//1.get classclass C = f.getclass ();//2.get ta ble Nameboolean exits = c.isannotationpresent (Table.class), if (!exits) {return null;} Table T = (table) c.getannotation (Table.class); String tableName = T.value (); Sb.append ("Select * from"). Append (TableName). Append ("where 1=1"); field[] Farray = C.getdeclaredfields ();for (Field Field:farray) {Boolean fexits = Field.isannotationpresent (Column.class); if (!fexits) {continue;} Column clolumn = field.getannotation (Column.class); String clolumnname = Clolumn.value (); String filedname = Field.getname (); String getmethodname = "Get" + filedname.substring (0, 1). toUpperCase () + filedname.substring (1, Filedname.length ()); O Bject Filedvalue = null;try {Method GetMethod = C.getmethod (getmethodname); filedvalue = Getmethod.invoke (f);} catch (Exce Ption e) {e.printstacktrace ();} if (Filedvalue = = NULL | | (Filedvalue instanceof integer && (integer) Filedvalue = = 0)) {continue;} Sb.append ("and"). Append (Filedname); if (Filedvalue instanceof String) {if ((String) filedvalue). Contains (",")) { String[] Filedvalues = (string) filedvalue). Split (","); Sb.append ("In ("); for (string value:filedvalues) {sb.append ("' "). Append (Value). Append (" ', ");} Sb.deletecharat (Sb.length ()-1); Sb.append (")");} else {sb.append ("="). Append (Filedvalue). Append ("'");}} else {sb.append (" = "). Append (Filedvalue);}} return sb.tostring ();}}

5. Test results

SELECT * from user where 1=1 and id = 1select * from user where 1=1 and userName = ' Stephen ' select * from user where 1=1 a nd email in (' [email protected] ', ' [email protected] ')



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Use of Java custom annotations

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.