注解中的抽象方法即是注解的属性。使用时先对属性赋值再获取属性值即可。
首先定义一个自己的注解
@Target(value = {ElementType.TYPE}) //作用于类上
@Retention(value = RetentionPolicy.RUNTIME) //作用于运行阶段
@Documented //表示定义的注解(MyAnno3)会被抽取到api文档
@Inherited //描述该注解(MyAnno3)会被子类继承
public @interface Pro {
String className(); //属性1(抽象方法)
String methodName(); //属性2(抽象方法)
}
@Target表示注解作用的位置,ElementType一般有三种取值,ElementType.TYPE表示该注解能作用在类上;ElementType.METHOD表示能作用在方法上;ElementType.FIELD表示能作用在属性上。
@Retention表示注解作用的阶段,RetentionPolicy有三种取值,RUNTIME表示运行阶段,CLASS表示类加载阶段,RESOURE表示源代码阶段。
@Documented表示定义的注解会被抽取到api文档
@Inherited描述该注解会被子类继承
使用并解析注解
@Pro(className = "Person.Student", methodName = "sleep") //给Pro注解的属性(抽象方法)赋值
public class Reflect {
public static void main(String[] args) throws Exception {
//获取使用注解的类的字节码对象
Class<Reflect> clathis = Reflect.class;
//获取指定注解对象
//本质是在内存中创建了一个该注解接口的子类实现对象
Pro pro = clathis.getAnnotation(Pro.class);
String className = pro.className();//获取注解的className属性
String methodName = pro.methodName();//获取注解的methodName属性
System.out.println(className);//打印Person.Student
System.out.println(methodName);//打印sleep
}