@Target(value ={ElementType.TYPE})//只能作用于类
@Retention(RetentionPolicy.RUNTIME)//在运行时起作用
public @interface StudentClassAnation {
String value() default "";//设置value属性的默认值为""
}
/**
* 数据库表中字段对应的属性
*
* 方法名来表是该注解的属性
* 方法返回类型作为属性的类型
*
*/
@Target(value = {ElementType.FIELD})//作用范围
@Retention(RetentionPolicy.RUNTIME)//作用时间
public @interface StudentFieldsAnatation {
String columnName();//列名
String type();//类型
int length();//长度
}
@StudentClassAnation("tb_student")//设置表名为"tb_student"
public class Student {
//设置表中列名为tc_name,类型为varchar,长度为20
@StudentFieldsAnatation(columnName = "tc_name",type="varchar",length = 20)
public String name;
@StudentFieldsAnatation(columnName = "tc_age",type="varchar",length = 10)
public int age;
@StudentFieldsAnatation(columnName = "tc_age",type="varchar",length = 5)
public int sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
}
public class Demo1 {
public static void main(String[] args) {
try {
Class clazz = Class.forName("com.anation.test.Student");
//获取所有的有效注解
Annotation[] annotations = clazz.getAnnotations();
for (int i = 0; i < annotations.length; i++) {
System.out.println(annotations[i]);
}
//获取指定的注解
StudentClassAnation annotation = (StudentClassAnation) clazz.getAnnotation(StudentClassAnation.class);
System.out.println(annotation);
//获得属性注解
Field field = clazz.getDeclaredField("name");
StudentFieldsAnatation studentFieldsAnatation = field.getAnnotation(StudentFieldsAnatation.class);
System.out.println("类型的长度:"+ studentFieldsAnatation.length());
} catch (Exception e) {
e.printStackTrace();
}
}
}