注解的继承

背景:当自定义注解遇到spring和类增强

注解的继承有些复杂,应尽量避免使用

当自定义注解遇到spring和类增强 第1点有改写方法遗失注解案例

 

public class TestMain {
public static void main(String []f) {

/**
* 结论
* 1 getMethods,getFields只能取到父类public
* 2 修饰类,要加@Inherited,常用于隐式的aop(cglib)
* 3 修饰public field,无论是否加@Inherited,都取得到
* 4 修饰public method override,无论是否加@Inherited,都取不到
* 5 修饰public method non override,无论是否加@Inherited,都取得到
* 6 修饰接口,无论是否加@Inherited,都取不到
*/

// 类
System.out.println(ByAnoCExtend.class.isAnnotationPresent(IJichen.class));
System.out.println(ByAnoCExtend.class.isAnnotationPresent(INonJichen.class));

// 成员
Field [] fields = ByAnoCExtend.class.getFields();
for(Field field : fields) {
field.setAccessible(true);

System.out.println(field.getName() + field.isAnnotationPresent(IJichen.class));
System.out.println(field.getName() + field.isAnnotationPresent(INonJichen.class));
}

// 方法
Method [] methods = ByAnoCExtend.class.getMethods();
for(Method method : methods) {
System.out.println(method.getName() + method.isAnnotationPresent(IJichen.class));
System.out.println(method.getName() + method.isAnnotationPresent(INonJichen.class));
}

// 接口
System.out.println(ByAnoIExtend.class.isAnnotationPresent(IJichen.class));
System.out.println(ByAnoIExtend.class.isAnnotationPresent(INonJichen.class));

}
}

像spring或guice使用cglib代理构建ioc的情况,需注意加到原始类的注解需要有@Inherit,运行期通过getBean().getClass().getAnnotation才能获得cglib代理生成的子类的注解

 

posted on 2020-08-01 18:11  silyvin  阅读(1780)  评论(0编辑  收藏  举报