標籤:java
最近學習了一下Java的自訂註解,終於知道了架構那些註解是咋個寫出來的了,以後我也可以自己寫架構,自己定義註解,聽著是不是很牛的樣子?不要心動,趕快行動,代碼很簡單,一起來學習一下吧!
這個例子是模仿架構的一個對sql拼裝的例子,用註解實現對model也就是實體類的注釋,就可以寫出查詢該欄位的sql.好了,廢話少說,一看代碼便知。大家可以根據自己的需求修改。
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 定義註解關鍵字 * 2. 元註解: * @Target:註解的範圍 * ElementType * TYPE:類介面聲明 * CONSTURCTOR:構造方法聲明 * FILED:欄位聲明 * LOCAL_VARIABLE:局部變數聲明 * METHOD:方法聲明 * PARCKAGE:包聲明 * PARMETER:參數聲明 * @Retention:註解的聲明周期 * RetentionPolicy * RUNTIME:運行時存在,可以通過反射讀取 * SOURCE:只在源碼顯示,編譯時間會丟棄 * CLASS:編譯時間會記錄到class中,運行時忽略 * @Inherited:允許子類繼承 * @Documented:產生javadoc時會包含註解 * 3. 使用自訂註解 * @<註解名>(<成員名1>=<成員值1>,<成員名2>=<成員值2>,...) * 如: * @MyAnnotation(name="Stephen.Huang", date="2015-7-30") * public void MyMethod() { * //TODO * } * * * @author Stephen Huang * @see http://blog.csdn.net/u010571844 * */@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Inherited@Documentedpublic @interface Table {/** * 1.成員以無參無異常聲明 * 2.可以用default為成員指定一個預設值,如:int age() default 18; * 3.成員類型是受限制的,合法的類型包括原始類型及String,Class,Annotation, Enumeration。 * 4.如果註解只有一個成員,則成員名必須取名為value(),在使用時可以忽略成員名和‘=’。 * 5.註解類可以沒有成員,沒有成員的註解稱為標註註解。 * @return */String value();}2.再定義資料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.定義User實體類
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.測試
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.setId(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 table 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());Object filedValue = null;try {Method getMethod = c.getMethod(getMethodName);filedValue = getMethod.invoke(f);} catch (Exception 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.測試結果
select * from user where 1=1 and id = 1select * from user where 1=1 and userName = 'Stephen'select * from user where 1=1 and email in ('[email protected]',' [email protected]')
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Java自訂註解的使用