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类型,它们被用来提供...