尚学堂210 反射机制读取注解
package com.bjsxt.test.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(value={ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface SxtTable { String value(); }
package com.bjsxt.test.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(value={ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface SxtField { String columnName(); String type(); int length(); }
package com.bjsxt.test.annotation; @SxtTable("tb_student") public class SxtStudent { @SxtField(columnName="id",type="int",length=10) private int id; @SxtField(columnName="sname",type="varchar",length=10) private String studentName; @SxtField(columnName="age",type="int",length=3) private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
package com.bjsxt.test.annotation; import java.lang.annotation.Annotation; import java.lang.reflect.Field; /** * 使用反射读取注解的信息,模拟处理注解信息的流程 * @author 尚学堂高淇 * */ public class Demo03 { public static void main(String[] args) { try { Class clazz = Class.forName("com.bjsxt.test.annotation.SxtStudent"); //获得类的所有有效注解 Annotation[] annotations=clazz.getAnnotations(); for (Annotation a : annotations) { System.out.println(a); } //获得类的指定的注解 SxtTable st = (SxtTable) clazz.getAnnotation(SxtTable.class); System.out.println(st.value()); //获得类的属性的注解 Field f = clazz.getDeclaredField("studentName"); SxtField sxtField = f.getAnnotation(SxtField.class); System.out.println(sxtField.columnName()+"--"+sxtField.type()+"--"+sxtField.length()); //根据获得的表名、字段的信息,拼出DDL语句,然后,使用JDBC执行这个SQL,在数据库中生成相关的表 } catch (Exception e) { e.printStackTrace(); } } }
程序运行的结果是:
@com.bjsxt.test.annotation.SxtTable(value=tb_student)
tb_student
sname--varchar--10
我们通过注解就可以获得对应的表名、字段的信息,我们就能够拼接处对应的sql语句,使用jdbc执行这个sql语言,在数据库中生成相关的表
posted on 2017-08-01 14:58 luzhouxiaoshuai 阅读(141) 评论(0) 编辑 收藏 举报