使用jdk获取注解信息
01 定义一个注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD})
public @interface Annotest {
String key();
String cacheName();
String backeupCacheName() default "";
boolean needlock() default false;
}
02 注解加到类或者方法字段上
@Annotest(key="class-key",cacheName = "class -cn")
public class Classtest {
@Annotest(key="fild-key",cacheName = "fild -cn")
private String test001;
@Annotest(key="method-key",cacheName = "method -cn")
public void test01(){}
}
03 反射获取注解中的信息
public class Testgetanno {
public static void main(String[] args) {
//类
Class<Classtest> cts = Classtest.class;
//打印类注解
Class<Annotest> ats= Annotest.class;
if (cts.isAnnotationPresent(ats)){
Annotest atsvo = cts.getAnnotation(ats);
System.out.printf(atsvo.key());
System.out.printf(atsvo.cacheName());
}
//打印方法注解信息
Method[] methods = cts.getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(ats)){
Annotest atsvo = method.getAnnotation(ats);
System.out.printf(atsvo.key());
System.out.printf(atsvo.cacheName());
}
}
}
}