概念:註解(Annotation),也叫元數據。一種代碼級別的說明。它是JDK1.5及以後版本引入的一個特性,與類、接口、枚舉是在同一個層次。它可以聲明在包、類、字段、方法、局部變量、方法參數等的前面,用來對這些元素進行說明,註釋。
1、元註解概念:註解的註解
2、自定義註解的語法要求
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Description{
String desc();
String author();
int age() default 18;
}
2.1 註解中成員類型是受限的,合法的類型包括原始類型及String,Class,Annotation,Enumeration
2.2 如果註解只有一個成員,則成員名必須取名爲value(),在使用時可以忽略成員名和複製號(=)
2.3 註解類可以沒有成員,沒有成員的註解稱爲標識註解
2.4 Target:註解作用域
·Constructor 構造方法聲明
·FIELD 字段聲明
·LOCAL_VARIABLE 局部變量聲明
·METHOD 方法聲明
·PACKAGE 包聲明
·PARAMETER 參數聲明
·TYPE 類聲明
2.5 Retention 生命週期
·SOURCE 只在源碼顯示,編譯時會丟棄
·CLASS 編譯時會記錄到class中,運行時忽略
·RUNTIME 運行時存在,可以通過反射讀取
2.6 Inherited 表示註解
2.7 Documented 生成javadoc時會包含註解
3、使用註解時的語法
@<註解名>(<成員名1>=<成員值1>,<成員名1>=<成員值1>,…)
@Decription(desc=”I am eyeColor”,author=”Mooc boy”,age=19)
public String eyeColor(){
return “red”;
}
4、解析註解:通過反射獲取類、函數或成員上的運行時註解信息,從而實現動態控制程序運行的邏輯
5、類上的註解繼承,子類只能繼承父類類的註解,而不能繼承方法上的註解
6、使用註解模擬PO對象生成sql語句:
Table註解:
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;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Table {
String value();
}
Column註解:
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;
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Column {
String value();
}
模擬PO:
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@Table("user")
public class Filter {
@Column("id")
private int id;
@Column("user_name")
private String userName;
@Column("nick_name")
private String nickName;
@Column("age")
private int age;
@Column("city")
private String city;
@Column("email")
private String email;
@Column("mobile")
private String mobile;
public static String query(Filter f){
StringBuilder sb = new StringBuilder();
//1.獲取到class
Class c = f.getClass();
//2.獲取到table的名字
boolean isExist = c.isAnnotationPresent(Table.class);
if(!isExist){
return null;
}
Table t = (Table)c.getAnnotation(Table.class);
String tableName = t.value();
sb.append("select * from ").append(tableName).append(" whre 1=1");
//3.遍歷所有的字段
Field[] fields = c.getDeclaredFields();
for(Field field:fields){
//4.處理每個字段對應的sql
//4.1 拿到每個字段名
boolean isExists = field.isAnnotationPresent(Column.class);
if(!isExists){
continue;
}
Column column = field.getAnnotation(Column.class);
//4.2拿到字段的值
String fieldName = field.getName();
String getMethodName = "get"+fieldName.substring(0, 1).toUpperCase() +
fieldName.substring(1);
Method getMethod = null;
try {
getMethod = c.getMethod(getMethodName);
} catch (NoSuchMethodException | SecurityException e) {
e.printStackTrace();
}
Object fieldValue = null;
try {
fieldValue = getMethod.invoke(f);
if(fieldValue instanceof Integer){
if((int)fieldValue != 0)
sb.append(" and ").append(column.value()).append(" = ").append(fieldValue);
}else if(fieldValue instanceof String){
if(((String) fieldValue).indexOf(",") > 0){
String[] arr = ((String) fieldValue).split(",");
sb.append(" and ").append(column.value()).append(" in(");
String inStr = "";
for(String s:arr){
inStr += "'" + s + "',";
}
inStr = inStr.substring(0, inStr.length()-1);
sb.append(inStr).append(")");
}else{
sb.append(" and ").append(column.value()).append(" like '%").append(fieldValue).append("%'");
}
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
//4.3 拼裝sql
//sb.append(" and ").append(column.value()).append(" = ").append(fieldValue);
}
return sb.toString();
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the userName
*/
public String getUserName() {
return userName;
}
/**
* @param userName the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* @return the nickName
*/
public String getNickName() {
return nickName;
}
/**
* @param nickName the nickName to set
*/
public void setNickName(String nickName) {
this.nickName = nickName;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the city
*/
public String getCity() {
return city;
}
/**
* @param city the city to set
*/
public void setCity(String city) {
this.city = city;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* @return the mobile
*/
public String getMobile() {
return mobile;
}
/**
* @param mobile the mobile to set
*/
public void setMobile(String mobile) {
this.mobile = mobile;
}
}
測試類:
Filter f1 = new Filter();
f1.setId(10);
Filter f2 = new Filter();
f2.setUserName("Jason");
f2.setAge(22);
Filter f3 = new Filter();
f3.setEmail("[email protected],[email protected],[email protected]");
String sql1 = Filter.query(f1);
String sql2 = Filter.query(f2);
String sql3 = Filter.query(f3);
System.out.println(sql1);
System.out.println(sql2);
System.out.println(sql3);