使用反射读取注解
package com.safecode;
@SxtTable("tb_student")
public class SxtStudent {
@SxtFiled(columName="id",type="int",length=10)
private int id;
@SxtFiled(columName="sname",type="varchar",length=10)
private String studentName;
@SxtFiled(columName="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.safecode;
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.safecode;
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 SxtFiled {
String columName();
String type();
int length();
}
package com.safecode;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
public class test {
public static void main(String[] args) {
try {
Class clazz = Class.forName("com.safecode.SxtStudent");
Annotation[] annotation = clazz.getAnnotations();
for(Annotation a: annotation) {
System.out.println(a);
}
SxtTable st = (SxtTable) clazz.getAnnotation(SxtTable.class);
System.out.println(st.value());
Field f = clazz.getDeclaredField("studentName");
SxtFiled sxtField = f.getAnnotation(SxtFiled.class);
System.out.println(sxtField.columName()+" "+sxtField.type()+ " "+ sxtField.length());
} catch (Exception e) {
e.printStackTrace();
}
}
}