Java reflection get annotations and Stitch SQL statements

Source: Internet
Author: User
Tags reflection

First two annotations are Table and Column, respectively

 Package com.hk.test; Import Java.lang.annotation.ElementType; Import java.lang.annotation.Retention; Import Java.lang.annotation.RetentionPolicy; Import Java.lang.annotation.Target; @Target ({elementtype.type}) @Retention (retentionpolicy.runtime)  public @Interface  Table {    String value ();}

  

 Package com.hk.test; Import Java.lang.annotation.ElementType; Import java.lang.annotation.Retention; Import Java.lang.annotation.RetentionPolicy; Import Java.lang.annotation.Target; @Target ({Elementtype.field}) @Retention (retentionpolicy.runtime)  public @Interface  Column {    String value ();}

Then create a new Bean Class Filter.java (this class can be changed according to your own needs, as long as the style is not changed)

 Packagecom.hk.test; @Table ("User") Public classFilter {@Column ("id")    Private intID; @Column ("User_name")    PrivateString UserName; @Column ("Age")    Private intAge ; @Column ("Email")    PrivateString Email;  Public intgetId () {returnID; }     Public voidSetId (intID) { This. ID =ID; }     PublicString GetUserName () {returnUserName; }     Public voidsetusername (String userName) { This. UserName =UserName; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicString Getemail () {returnemail; }     Public voidsetemail (String email) { This. email =email; }    }

Then test the class

 Packagecom.hk.test;ImportJava.lang.reflect.Field;ImportJava.lang.reflect.Method;/** *  * @authorHk_z *@deprecatedreflection on a class get annotations and field names stitched into SQL statements *@version0.1*/ Public classTest { Public Static voidMain (string[] args) {Filter F1=NewFilter (); F1.setid (10); Filter F2=NewFilter (); F2.setusername ("Lucy");//Fuzzy QueryFilter f3=NewFilter (); F3.setemail ("[Email Protected],[email protected]");//any oneString SQL1=query (F1);        System.out.println (SQL1); String SQL2=query (F2);        System.out.println (SQL2); String Sql3=query (F3);    System.out.println (SQL3); }    Private StaticString Query (Filter F1) {//TODO auto-generated Method StubStringBuilder SB =NewStringBuilder (); //1. Get to ClassClass C =F1.getclass (); //2. Get the name of the table        Booleanexists = C.isannotationpresent (Table.class);//There are no table annotations in class        if(!exists) {            return NULL; } Table T= (table) c.getannotation (table).class); String TableName= T.value ();//Table nameSb.append ("SELECT * from"). Append (TableName). Append ("Where 1 = 1"); //3. Iterate through all the fieldsfield[] Farray =C.getdeclaredfields ();  for(Field field:farray) {//4. Handle the SQL for each field//4.1 Get field name            BooleanFexists = Field.isannotationpresent (Column.class); if(!fexists) {                Continue; } Column Column= Field.getannotation (Column.class); String ColumnName= Column.value ();//the name of the field inside the table//4.2 Get the value of the fieldString filedname = Field.getname ();//the name of the variableString getmethodname = "Get" +filedname.substring (0,1). toUpperCase () +filedname.substring (1); Object Fieldvalue=NULL; //Assemble get method to get return value;            Try{Method GetMethod= C.getmethod (Getmethodname);//ReflectionFieldvalue = Getmethod.invoke (F1);//Reflection Call                            } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); }            //4.3 assembling SQL            if(Fieldvalue = =NULL|| (FieldvalueinstanceofInteger && (integer) fieldvalue==0))            {                Continue; } sb.append ("and"). Append (Filedname); String [] Val=NULL; if(FieldvalueinstanceofString) {//string type and have commas to split                if((String) fieldvalue). Contains (",") ) {Val= (String) fieldvalue. Split (","); Sb.append ("In (");  for(String v:val) {sb.append ("'"). Append (v). Append ("'"). Append (","); } Sb.deletecharat (Sb.length ()-1); Sb.append (")"); }                Else{sb.append ("="). Append ("'"). Append (Fieldvalue). Append ("'"); }            }            Else if(FieldvalueinstanceofInteger) {Sb.append (" = "). Append (Fieldvalue); }                    }        returnsb.tostring (); }}

Java reflection get annotations and Stitch SQL statements

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.