注解解析:
package java.lang.reflect.AnnotatedElement接口
它有很多实现类:CLass、Method、Field、Constructor等都实现了该接口
- <T extends Annotation> T getAnnotation(Class<T> annotationClass)
得到指定类型的注解引用,没有返回null
- default boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
判断指定的注解有没有
案例演示:
需求:获取Test类上的注解对象
// 自定义注解
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String[] names();
int age();
}
// Test类
@MyAnnotation(names = {"张三"},age = 18)
public class Test {
public static void main (String[] args) throws NoSuchMethodException {
// 需求:获取Test类上的注解对象,并且获得该注解的属性值
// 1.获取Tests类的Class对象
Class<Test> testClass = Test.class;
// 2.获取该Class对象上的注解对象
MyAnnotation annotation = testClass.getAnnotation(MyAnnotation.class);
// 根据注解对象获取该注解的属性值
String[] names = annotation.names();
System.out.println(Arrays.toString(names));
int age = annotation.age();
System.out.println(age);
System.out.println("======================================");
// 需求2:获取show1方法上的注解对象,并且获取该注解的属性值
// 1.获取show1方法的Mthod对象
Method show1 = testClass.getDeclaredMethod("show1");
// 2.获取该方法上的注解
MyAnnotation annotation1 = show1.getAnnotation(MyAnnotation.class);
// 3.根据注解获取属性上的值
System.out.println(Arrays.toString(annotation1.names()));
System.out.println(annotation1.age());
System.out.println("======================================");
// 需求3:判断Tetsts类中的方法是否包含MyAnnotatio注解
// 1.获取show2方法的Method对象
Method show2 = testClass.getDeclaredMethod("show2");
// 2.判断show2方法是否包含MyAnnotation注解
System.out.println(show2.isAnnotationPresent(MyAnnotation.class));
System.out.println(show1.isAnnotationPresent(MyAnnotation.class));
MyAnnotation annotation2 = show2.getAnnotation(MyAnnotation.class);
System.out.println(annotation2);// null
}
@MyAnnotation(names = {"李四"},age = 18)
public void show1(){
}
public void show2(){
}
}
输出结果:
[张三]
18
======================================
[李四]
18
======================================
false
true
null