使用Java反射(Reflect)、自訂註解(Customer Annotation)產生簡單SQL語句,reflectannotation

來源:互聯網
上載者:User

使用Java反射(Reflect)、自訂註解(Customer Annotation)產生簡單SQL語句,reflectannotation

這次給大家介紹一下在Java開發過程中 使用自訂註解開發:
主要知識點:
            1.反射            主要用於提取註解資訊
            2.自訂異常  主要是為了自己自訂一個異常資訊
            3.自訂註解  本次重點 學會如何自訂註解以及如何使用反射提取註解資訊運用到實際開發
表示在Java中註解的含義以及註解的分類和如何解析註解

 

通常我們使用自訂註解一般使用4中元註解即:
@Target
@Retention
@Documented
@Inherited

 

  1 **  2  *   3  */  4 /**  5  * ClassName:package-info.java  6  * @author xg.qiu  7  * @since JDK1.7  8  * Aug 3, 2015  9  * 使用自訂註解: 10  * @Target :用於描述註解的使用範圍(即:被描述的註解可以用在什麼地方) 11  * 取值(ElementType)有: 12         1.ElementType.CONSTRUCTOR:用於描述構造器 13         2.ElementType.FIELD:用於描述域 14         3.ElementType.LOCAL_VARIABLE:用於描述局部變數 15         4.ElementType.METHOD:用於描述方法 16         5.ElementType.PACKAGE:用於描述包 17         6.ElementType.PARAMETER:用於描述參數 18         7.ElementType.TYPE:用於描述類、介面(包括註解類型) 或enum聲明 19   @Retention :@Retention定義了該Annotation被保留的時間長短 20   取值(RetentionPoicy)有: 21     1.RetentionPolicy.SOURCE:在源檔案中有效(即源檔案保留) 22     2.RetentionPolicy.CLASS:在class檔案中有效(即class保留) 23     3.RetentionPolicy.RUNTIME:在運行時有效(即運行時保留) 24   @Documented:用於描述其它類型的annotation應該被作為被標註的程式成員的公用API, 25                   因此可以被例如javadoc此類的工具文檔化。 26                   Documented是一個標識註解,沒有成員。 27   @Inherited :元註解是一個標記註解,@Inherited闡述了某個被標註的類型是被繼承的 28                   [必須是extend class 而不是implements interface] 29  */ 30 package com.demo.ann; 31  32 註解文法: 33 public @interface 註解名{ 34     35         // 註解變數 36        // 中繼資料類型:基礎資料型別 (Elementary Data Type) String class enum Annotation 以及上述類型數組 37        // 如果中繼資料只有一個時 必須聲明為value(); 38 } 39  40 /** 41  *  42  */ 43 package com.demo.ann.anns; 44  45 import java.lang.annotation.ElementType; 46 import java.lang.annotation.Retention; 47 import java.lang.annotation.RetentionPolicy; 48 import java.lang.annotation.Target; 49  50 /** 51  * ClassName:Table.java 52  * @author xg.qiu 53  * @since JDK1.7 54  * Aug 3, 2015 55  * 自訂註解:表 56  * 用法: 57  *  @Table("user") 58  *     public class User 59  */ 60  61 @Target( ElementType.TYPE)// 範圍 類或介面 62 @Retention( RetentionPolicy.RUNTIME)// 有效期間為運行時 63 public @interface Table { 64     String value(); 65 } 66  67  68  69 /** 70  *  71  */ 72 package com.demo.ann; 73  74 import com.demo.ann.anns.Column; 75 import com.demo.ann.anns.Table; 76  77 /** 78  * ClassName:User.java 79  * JAVABean 使用者實體類 80  * @author xg.qiu 81  * @since JDK1.7 Aug 3, 2015 82  */ 83 @Table("TABLE_USER") 84 public class User { 85     @Column("USER_ID") 86     private int userId; 87     @Column("USER_NAME") 88     private String userName; 89     @Column("PASS_WORD") 90     private String passWord; 91     @Column("AGE") 92     private int age; 93  94     public int getUserId() { 95         return userId; 96     } 97  98     public void setUserId(int userId) { 99         this.userId = userId;100     }101 102     public String getUserName() {103         return userName;104     }105 106     public void setUserName(String userName) {107         this.userName = userName;108     }109 110     public String getPassWord() {111         return passWord;112     }113 114     public void setPassWord(String passWord) {115         this.passWord = passWord;116     }117 118     public int getAge() {119         return age;120     }121 122     public void setAge(int age) {123         this.age = age;124     }125 }126 127  128 /**129  * 130  */131 package com.demo.ann.anns;132 133 import java.lang.annotation.ElementType;134 import java.lang.annotation.Retention;135 import java.lang.annotation.RetentionPolicy;136 import java.lang.annotation.Target;137 138 /**139  * ClassName:Column.java140  * @author xg.qiu141  * @since JDK1.7142  * Aug 3, 2015143  * 自訂註解:列144  * 用法:145  *         @Column("userId")146  *         private int userId;147  */148 @Target( ElementType.FIELD)//作用於屬性149 @Retention( RetentionPolicy.RUNTIME)//有效期間為運行時150 public @interface Column {151     String value();152 }153  154 155 156 157 158 /**159  160  * 161  */162 package com.demo.ann;163 164 import java.lang.reflect.Field;165 import java.lang.reflect.Method;166 167 import com.demo.ann.anns.Column;168 import com.demo.ann.anns.Table;169 import com.demo.ann.exception.AnnException;170 171 /**172    解析註解並返回執行的sql語句 173  * ClassName:Test.java174  * @author xg.qiu175  * @since JDK1.7176  * Aug 3, 2015177  * 測試:使用自訂註解完成資料庫的查詢返回sql語句178  *         1.根據id查詢179  *         2.根據使用者名稱查詢180  *         3.根據使用者名稱、密碼組合查詢181  */182 public class Test {183     public static void main(String[] args) {184         User user1 = new User();185         user1.setUserId(1);//根據Id查詢186         187         User user2 = new User();188         user2.setUserName("xiaoqiu");// 根據使用者名稱查詢189         190         User user3 = new User();191         user3.setUserName("xiaoqiu");192         user3.setPassWord("123456");// 根據使用者名稱、密碼組合查詢193         194         User user4 = new User();195         user4.setUserName("xiaoqiu,zasang,lisi");196         197         String sql1 = executeQuery(user1);198         String sql2 = executeQuery(user2);199         String sql3 = executeQuery(user3);200         String sql4 = executeQuery(user4);201         202         System.out.println(sql1);203         System.out.println(sql2);204         System.out.println(sql3);205         System.out.println(sql4);206         207     }208          /**209           * @param user 使用者物件210           *@return String 返回的是拼裝好的sql語句211           */212     private static String executeQuery(User user) {213         StringBuffer sb = new StringBuffer("select * from ");214         //1、擷取類215         Class<? extends User> c = user.getClass();216         //2、尋找類是否被註解217         boolean isExist = c.isAnnotationPresent(Table.class);218         if(!isExist){219             try {220                                 // 自訂異常221                 throw new AnnException("the "+ c.getClass().getName() +" class is not used annotation");222             } catch (AnnException e) {223                 e.printStackTrace();224             }225         }226                 // 擷取Table註解 227         Table table = (Table) c.getAnnotation(Table.class);228         sb.append( table.value() +" where 1= 1");229         //3、尋找屬性是否被註解230         Field[] fields = c.getDeclaredFields();231         for(Field f : fields){232             //3.1、處理每個欄位對應的sql233             //3.2、拿到欄位值234             boolean isFExist = f.isAnnotationPresent(Column.class);235             if(!isFExist){236                 try {237                     throw new AnnException("the " + f.getName()  +" field is not used annotation");238                 } catch (AnnException e) {239                     e.printStackTrace();240                 }241             }242                         // 擷取列註解 243             Column column = f.getAnnotation(Column.class);244             String columnName = column.value();245             //3.2、擷取欄位246             String fieldName = f.getName();247             //3.4、.拿到欄位值248             Object values = null;249             String getFieldMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);250             try {251                 Method getMethod = c.getDeclaredMethod(getFieldMethodName);252                 values = getMethod.invoke(user);253                 //3.5.拼裝sql254                 if( values == null || ( values instanceof Integer && (Integer) values == 0) ){255                     continue;256                 }257                 sb.append(" and ").append(columnName);258                 if(values instanceof Integer){259                     sb.append("=").append(values);260                 }else if(values instanceof String){261                     if( ((String) values).contains(",")){262                         String [] valuesIn = ((String) values).split(",");263                         sb.append(" in('");264                         for(String s : valuesIn){265                             sb.append(s).append("'").append(",");266                         }267                         sb.deleteCharAt(sb.length() - 1);268                         sb.append(")");269                     }else{270                         sb.append("='").append(values).append("'");271                     }272                 }273             } catch (Exception e) {274                                  // 列印堆棧資訊 275                 e.printStackTrace();276             }277         }278                 // 返回拼裝好的sql語句 279         return sb.toString();280     }281 }

運行效果:
 
select * from TABLE_USER where 1= 1 and USER_ID=1select * from TABLE_USER where 1= 1 and USER_NAME='xiaoqiu'select * from TABLE_USER where 1= 1 and USER_NAME='xiaoqiu' and PASS_WORD='123456'select * from TABLE_USER where 1= 1 and USER_NAME in('xiaoqiu',zasang',lisi')

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.