注解的繼承有些復雜,應盡量避免使用
當自定義注解遇到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代理生成的子類的注解