注解的本质
- 注解的本质即为接口,可通过以下代码验证:
public class Test { public static void main(String[] args) { Class clazz=Anno02.class; System.out.println("是否是接口"); System.out.println(clazz.isInterface());//true System.out.println("===========继承那个接口============="); Class[] cs=clazz.getInterfaces(); for (Class class1 : cs) { System.out.println(class1);//java.lang.annotation.Annotation } System.out.println("==========方法============"); /** * 反射时候看到的注解属性就是方法: * public abstract java.lang.String cn.edu.xcu.annotation.v2.Anno02.m() */ Method[] ms=clazz.getMethods(); for (Method method : ms) { System.out.println(method); } System.out.println("==========字段============"); Field[] fs=clazz.getFields(); for (Field field : fs) { System.out.println(field); } } }
反射读取属性值
- 意义:因为注解是让工具看的,我们框架要读取配置的属性值,要通过反射读取。
- 定义:
@Retention(RetentionPolicy.RUNTIME)
public @interface Anno {
public String attr1();
public String[] attr2();
}
- 使用
@Anno(attr1="dasb",attr2={"dasb1","dasb2"})
public class A {
}
- 读取
public class Test01 {
public static void main(String[] args) {
//1 找到像
Class clazz=A.class;
//2 找到注解出现位置
Anno anno=(Anno) clazz.getDeclaredAnnotation(Anno.class);
System.out.println(anno.getClass());//jdk 代理
//3 调用
String attr1=anno.attr1();
System.out.println(attr1);
System.out.println("===================");
String[] attr2=anno.attr2();
for (String string : attr2) {
System.out.println(string);
}
}
}