TestStudent.java 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package com.sf.javase.anno;
  2. import java.lang.annotation.Annotation;
  3. import java.lang.reflect.Field;
  4. /**
  5. * 通过注解 构造对表的查询语句
  6. * 通过反射来获取注解中的值
  7. * 然后进行逻辑处理 (注解+反射)
  8. */
  9. public class TestStudent {
  10. public static void main(String[] args) {
  11. // 获取类对象
  12. Class<Student> studentCls = Student.class;
  13. // 接收类对象的所有注解
  14. Annotation[] annotations = studentCls.getAnnotations();
  15. // 能够指定注解的类型 拿到注解对象
  16. // @Table("student")
  17. Table table = studentCls.getAnnotation(Table.class);
  18. // 可以通过注解对象 获取注解中配置的数据
  19. String tableName = table.value();
  20. System.out.println(tableName);
  21. // 获取全部的属性 id name
  22. Field[] fields = studentCls.getDeclaredFields();
  23. StringBuffer buffer = new StringBuffer();
  24. buffer.append("select ");
  25. for (Field field : fields) {
  26. // 通过属性来获取注解
  27. Column column = field.getAnnotation(Column.class);
  28. String columnName = column.columnName();
  29. // String type = column.columnType();
  30. buffer.append(columnName);
  31. buffer.append(",");
  32. }
  33. // select id,name,
  34. buffer.deleteCharAt(buffer.length() - 1);
  35. // select id,name
  36. buffer.append(" from ");
  37. buffer.append(tableName);
  38. // select id,name from student
  39. System.out.println(buffer);
  40. }
  41. }