注解在源码里常用,接下来实战如何通过Class获取Annotation
/**
* 注解一
*/
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyAnnotation {
}
/**
* 注解二
*/
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyAnnotation2 {
}
新建两个反射对象,继承关系
@MyAnnotation
public class ReflectionClassesModel extends AbstractReflectionClassesModel {
public ReflectionClassesModel() {
}
}
@MyAnnotation2
public class AbstractReflectionClassesModel implements Cloneable, Serializable {
public AbstractReflectionClassesModel() {
}
}
1、测试获取Class注解
public class ReflectionTest4 {
public static void main(String[] args) {
Class<ReflectionClassesModel> reflectionClassesModelClass = ReflectionClassesModel.class;
// 获取注解包含父类
Annotation[] annotations = reflectionClassesModelClass.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation.annotationType().getName());
}
System.out.println("============================");
// 获取注解不包含父类
Annotation[] declaredAnnotations = reflectionClassesModelClass.getDeclaredAnnotations();
for (Annotation annotation : declaredAnnotations) {
System.out.println(annotation.annotationType().getName());
}
}
}
打印日志:
com.pss.model.MyAnnotation2
com.pss.model.MyAnnotation
============================
com.pss.model.MyAnnotation
2、获取class是否存在某一个注解
// 判断类是否存在注解
boolean annotationPresent = reflectionClassesModelClass.isAnnotationPresent(MyAnnotation.class);
boolean annotationPresent2 = reflectionClassesModelClass.isAnnotationPresent(MyAnnotation2.class);
System.out.println(annotationPresent);
System.out.println(annotationPresent2);
从打印结果看出判断Class是否存在注解的时候,是会查找父类的注解
打印结果:
true
true
3、获取字段的注解
// 获取字段注解,因为源码是使用同一个方法,所以结果一致
Field[] fields = reflectionClassesModelClass.getFields();
for (Field f : fields) {
f.setAccessible(true);
Annotation[] annotations = f.getDeclaredAnnotations();
System.out.println(annotations.length);
Annotation[] annotations2 = f.getAnnotations();
System.out.println(annotations2.length);
}
打印结果:
1
1
4、获取方法的注解
// 获取方法注解,因为源码是使用同一个方法,所以结果一致
Method[] methods = reflectionClassesModelClass.getDeclaredMethods();
for (Method m : methods) {
m.setAccessible(true);
Annotation[] annotations = m.getDeclaredAnnotations();
System.out.println(annotations.length);
Annotation[] annotations2 = m.getAnnotations();
System.out.println(annotations2.length);
}
打印结果:
1
1