获取注解的值
- 使用getAnnotation方法来获取到注解
- 获取到注解后就可以获取值
自定义的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Test_db{
String value();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Test_db_c{
String colname();
String type();
int length();
}
Class<?> class1 = Class.forName("test03.Student");
//获取class所有的注解
Annotation[] annotations = class1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
//获取class的指定的注解
Test_db test_db = (Test_db) class1.getAnnotation(Test_db.class);
//获取注解的值
String value = test_db.value();
System.out.println(value);
//获取指定的属性
Field field = class1.getDeclaredField("id");
//获取属性的指定的注解
Test_db_c test_db_c = field.getAnnotation(Test_db_c.class);
System.out.println(test_db_c.colname());
System.out.println(test_db_c.length());
System.out.println(test_db_c.length());
@Test_db("db_student")
class Student {
@Test_db_c(colname = "db_id",type="int",length=10)
int id;
@Test_db_c(colname = "db_name",type="varchar",length=10)
String name;
@Test_db_c(colname = "db_age",type="int",length=10)
int age;
}