123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- package com.sf.javase.anno;
- import java.lang.annotation.Annotation;
- import java.lang.reflect.Field;
- /**
- * 通过注解 构造对表的查询语句
- * 通过反射来获取注解中的值
- * 然后进行逻辑处理 (注解+反射)
- */
- public class TestStudent {
- public static void main(String[] args) {
- // 获取类对象
- Class<Student> studentCls = Student.class;
- // 接收类对象的所有注解
- Annotation[] annotations = studentCls.getAnnotations();
- // 能够指定注解的类型 拿到注解对象
- // @Table("student")
- Table table = studentCls.getAnnotation(Table.class);
- // 可以通过注解对象 获取注解中配置的数据
- String tableName = table.value();
- System.out.println(tableName);
- // 获取全部的属性 id name
- Field[] fields = studentCls.getDeclaredFields();
- StringBuffer buffer = new StringBuffer();
- buffer.append("select ");
- for (Field field : fields) {
- // 通过属性来获取注解
- Column column = field.getAnnotation(Column.class);
- String columnName = column.columnName();
- // String type = column.columnType();
- buffer.append(columnName);
- buffer.append(",");
- }
- // select id,name,
- buffer.deleteCharAt(buffer.length() - 1);
- // select id,name
- buffer.append(" from ");
- buffer.append(tableName);
- // select id,name from student
- System.out.println(buffer);
- }
- }
|