
- 用户昵称:aflfte2011
新建注解信息
package com.aflfte.test.annotation;
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 创建属性与对应字段注解方便解析 * @author aflft * */ @Target(value=ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface AflfteField { String clumnName(); String type(); int length(); }
//创建数据类
package com.aflfte.test.annotation;@Table("tb_student") public class Student { @AflfteField(clumnName = "id",type = "int",length = 10) private int id; @AflfteField(clumnName = "sname",type = "varchar",length = 10) private String studentName; @AflfteField(clumnName = "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.aflfte.test.annotation; import java.lang.annotation.Annotation; /** * 使用反射读取注解信息,模拟处理注解信息的流程 * * @author aflft * */ public class Demo03 { public static void main(String[] args) { try { Class cla=Class.forName("com.aflfte.test.annotation.Student"); //获取类的所有注解 Annotation[] annotation=cla.getAnnotations(); for(Annotation a:annotation) { System.out.println(a); } //获得类指定注解的值 Table table=(Table)cla.getAnnotation(Table.class); System.out.println(table.value()); //获得类的属性注解 java.lang.reflect.Field[] fs=cla.getDeclaredFields(); /*Field field=f.getAnnotation(Field.class); System.out.println(field.clumnName()+"-->"+field.type()+"-->"+field.length());*/ //根据获得的表名、字段的信息,拼出DDL语句,然后使用JDBC执行这个SQL在数据库中生成相关的表 StringBuilder sql=new StringBuilder(); sql.append("CREATE TABLE ").append(table.value()).append(" (\r\n"); for(java.lang.reflect.Field f:fs) { AflfteField fie=f.getAnnotation(AflfteField.class); sql.append(fie.clumnName()+" "+fie.type()+"("+fie.length()+") NOT NULL,\r\n"); } sql.append(")"); System.out.println(sql.toString()); } catch (Exception e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } } |