java 反射注解信息
发布时间:2020-12-15 07:48:20 所属栏目:Java 来源:网络整理
导读:Table,用类表示数据库的表 @Target(value= {ElementType.METHOD,ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)public @interface Table{ String value();} 类中的属性,每个属性表示一个字段 @Target(value= ElementType.FIELD) @Retention(Reten
Table,用类表示数据库的表
@Target(value= {ElementType.METHOD,ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Table{ String value(); } 类中的属性,每个属性表示一个字段 @Target(value= ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Fields { String columnName(); String type(); int length(); } 类: @Table("tb_student") public class Student { @Fields(columnName="id",type="int",length=10) private int id; @Fields(columnName="studentName",type="varchar",length=10) private String studentName; @Fields(columnName="age",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; } } 解析器: public class Deam { public static void main(String[] args) throws InstantiationException,IllegalAccessException,IllegalArgumentException,InvocationTargetException,NoSuchMethodException,SecurityException,NoSuchFieldException { try { Class c=Class.forName("cn.sxt.in.Student"); Annotation[] annotation= c.getAnnotations(); //获得类的所有注解,只是类的,不包括方法等 for(Annotation a:annotation) { System.out.println(a); } //获得指定类的注解 Table tb=(Table) c.getAnnotation(Table.class); System.out.println(tb.value()); //获得属性的注解 Field f=c.getDeclaredField("studentName"); //通过内容返回属性 Fields f2=f.getAnnotation(Fields.class); //通过属性返回注解 System.out.println(f2.columnName()+"-->"+f2.type()+"-->"+f2.length()); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |