import DAO.Filter;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Main {
//
public static void main(String[] args) {
Main main = new Main();
main.setup();
}
//
void setup() {
Filter f1 = new Filter();
f1.setId("10");
try {
String text = query(f1);
System.out.println(text);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
String query(Filter filter) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
StringBuffer stringBuffer = new StringBuffer();
//获取class
Class c = filter.getClass();
boolean isExist = c.isAnnotationPresent(Table.class);
if (isExist == false) {
return null;
}
Table table = (Table) c.getAnnotation(Table.class);
String tableName = table.value();
stringBuffer.append("select * from ").append(tableName).append(" where 1 = 1 ");
//遍历
Field[] fields = c.getDeclaredFields();
for (Field field:fields) {
boolean iscolum = field.isAnnotationPresent(Column.class);
if (iscolum == false) {
continue;
}
Column column = field.getAnnotation(Column.class);
String name = column.value();
//拿到字段和get方法
String fieldName = field.getName();
String getMethodName = "get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
//执行method
Method getMethod = c.getMethod(getMethodName);
String fieldValue = (String) getMethod.invoke(filter);
if (fieldValue == null) {
continue;
}
//拼接sql
stringBuffer.append(" and ").append(fieldName).append(" = ").append(fieldValue);
}
return stringBuffer.toString();
}
}
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface Column {
String value();
}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface Table {
String value();
}
网友评论