概念:注解(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("wang@sina.com,zh@163.com,9999@qq.com");
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);