@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String name() default "xx";
int age();
}
public class Person {
@MyAnnotation(name = "张三",age = 15)
public static void show(){
try {
//1.获取反射类对对象
Class<?> class1 = Class.forName("com.qf.day22_exer.Person");
//2.获取show方法
Method show = class1.getMethod("show");
//3.获取方法的注解
MyAnnotation annotation = show.getAnnotation(MyAnnotation.class);
//4.获取姓名和年龄
System.out.println(annotation.name());
System.out.println(annotation.age());
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class TestPerson {
public static void main(String[] args) {
Person p = new Person();
p.show();
}
}
注解的本质就是接口,注解中的属性是抽象方法 我们可以用反编译工具来查看