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();
}
java注解
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 目录 【Android】注解框架(一)-- 基础知识Java 反射 【Android】注解框架(二)-- 基础知...
- 概要 这篇文章将会带领你了解Java注解,注解的使用,注解的解析,利用反射解析运行时注解,相信有一定Java基础的...
- 元注解的作用就是负责注解其他注解。Java5.0定义了4个标准的meta-annotation类型,它们被用来提供...