利用Java反射机制读取注解

小咪咪 2022-05-14 14:39 275阅读 0赞

java代码:

  1. package ORM;
  2. @SxtTable("tb_student")
  3. public class SxtStudent {
  4. @SxtField(columnName="id", type="int", length=10)
  5. private int id;
  6. @SxtField(columnName="sname", type="varchar", length=10)
  7. private String studentName;
  8. @SxtField(columnName="age", type = "int", length=3)
  9. private int age;
  10. public int getId() {
  11. return id;
  12. }
  13. public void setId(int id) {
  14. this.id = id;
  15. }
  16. public String getStudnet() {
  17. return studentName;
  18. }
  19. public void setStudnet(String studnet) {
  20. this.studentName = studnet;
  21. }
  22. public int getAge() {
  23. return age;
  24. }
  25. public void setAge(int age) {
  26. this.age = age;
  27. }
  28. }

自定义注解:

  1. package ORM;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. import java.lang.annotation.Target;
  6. import javax.lang.model.element.Element;
  7. @Target(value = ElementType.FIELD) //此注解能用于类 接口 枚举 Annotation类型之前
  8. @Retention(RetentionPolicy.RUNTIME) //表示此注解可以被反射机制读取
  9. public @interface SxtField {
  10. String columnName();
  11. String type();
  12. int length();
  13. }
  14. package ORM;
  15. import java.lang.annotation.ElementType;
  16. import java.lang.annotation.Retention;
  17. import java.lang.annotation.RetentionPolicy;
  18. import java.lang.annotation.Target;
  19. import javax.lang.model.element.Element;
  20. @Target(value = ElementType.TYPE) //此注解能用于类 接口 枚举 Annotation类型之前
  21. @Retention(RetentionPolicy.RUNTIME) //表示此注解可以被反射机制读取
  22. public @interface SxtTable {
  23. String[] value();
  24. }

通过class获取注解信息:

  1. package ORM;
  2. import java.lang.annotation.Annotation;
  3. import java.lang.reflect.Field;
  4. /**
  5. * 使用反射读取注解信息,模拟处理注解信息的流程
  6. * @author lenovo
  7. *
  8. */
  9. public class ORM {
  10. public static void main(String[] args) {
  11. try {
  12. Class clazz = Class.forName("ORM.SxtStudent"); //返回一个反射对象
  13. Annotation[] annotations = clazz.getAnnotations(); //获得类的全部注解即@SxtTable("tb_student")
  14. for(Annotation a: annotations) {
  15. System.out.println(a);
  16. }
  17. //获得类指定的注解
  18. SxtTable st = (SxtTable) clazz.getAnnotation(SxtTable.class);
  19. System.out.println(st.value());
  20. //获得类的属性注解
  21. Field f = clazz.getDeclaredField("studentName");
  22. SxtField sxtField = f.getAnnotation(SxtField.class);
  23. System.out.println(sxtField.columnName() + "--" + sxtField.type() + "--" + sxtField.length());
  24. //根据获得的表名, 字段信息, 拼出DDL语句, 使用JDBC执行SQL语句, 在数据库中生成相关的表
  25. } catch (Exception e) {
  26. e.printStackTrace();
  27. }
  28. }
  29. }

结果:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dhbmdqaWFuNTMw_size_27_color_FFFFFF_t_70

发表评论

表情:
评论列表 (有 0 条评论,275人围观)

还没有评论,来说两句吧...

相关阅读