import java.lang.annotation.*;
/**
* @Author: www.itze.cn
* @Date: 2020/09/13 14:58
* @Email: 814565718@qq.com
*/
/**
* @Target:注解的作用范围,METHOD:作用在方法上,TYPE:作用在类上
* @Retention:注解的生命周期,RUNTIME:运行时
* @Inherited:子类继承父类,只能解析到类层,方法层解析不到
*/
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Desc {
//成员组成必须是无参/无异常
String value();
}
/**
* @Author: www.itze.cn
* @Date: 2020/09/13 15:20
* @Email: 814565718@qq.com
*/
@Desc(value = "This is DescMethod Class")
public class DescMethod {
@Desc(value = "This is A Method")
public void A(){}
@Desc(value = "This is B Method")
public void B(){}
}
public static void main(String[] args) {
/**
* 解析注解
* 获取类上的注解内容
*/
Class<DescMethod> methodClass = DescMethod.class;
boolean classAnnotationPresent = methodClass.isAnnotationPresent(Desc.class);
//如果DescMethod.class中存在@Desc注解
if (classAnnotationPresent) {
//获取@Desc注解
Desc annotation = methodClass.getDeclaredAnnotation(Desc.class);
//得到@Desc注解中的内容
String desc = annotation.value();
System.out.println(desc);
}
/**
* 解析注解
* 获取类中方法上的注解内容
*/
//获取类中所有方法
Method[] methods = methodClass.getDeclaredMethods();
for (Method method : methods
) {
boolean methodAnnotationPresent = method.isAnnotationPresent(Desc.class);
//如果该方法上存在@Desc注解
if (methodAnnotationPresent) {
//获取@Desc注解
Desc annotation = method.getDeclaredAnnotation(Desc.class);
//得到该方法上@Desc注解的内容
String desc = annotation.value();
System.out.println(desc);
}
}
}