反射获得注解
反射获得注解
@Retention(RetentionPolicy.RUNTIME)是必须要加上去的,这个是运行时获得注解,反射执行需要他
调取注解时,要获取注解所解释的元素,如要获取类注解,则先获取这个类的class,获取属性,则要获取属性
若要获取注解的值,则要把所得到的注解强转为自定义注解类型,然后调用里面的属性即可(相当于调取类属性)
import java.lang.annotation.*;
import java.lang.reflect.Field;
public class Test {
public static void main(String[] args) {
try {
Class clazz = Class.forName("com.geek.pritice.Father");
for (Annotation annotation : clazz.getDeclaredAnnotations()) {
Good good = (Good)annotation;
System.out.println(good.value());
}
Field a = clazz.getDeclaredField("a");
Good good1 = a.getDeclaredAnnotation(Good.class);
System.out.println(good1.value());
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Good(value = "888")
class Father{
@Good(value = "20")
int a = 10;
}
@Target({ElementType.TYPE,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface Good{
String value();
}

浙公网安备 33010602011771号