关于元注解@Inherited的探究
来源:互联网 发布:深度卷积网络 dcnn 编辑:程序博客网 时间:2024/05/21 16:54
学习中发现采用本文探讨的元注解注解的自定义注解,位于接口中或父类里的方法上的注解不是都能被继承下来的。
我做的试验时:(只列举父类中的方法上的自定义注解无法被继承这种情况,稍加改动即可做关于接口中的方法无法被继承下来的试验。)
这是自定义注解类
package cn.it.test;import java.lang.annotation.ElementType;import java.lang.annotation.Inherited;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Inherited//希望子类可以继承public @interface myannotation{public String value();}
这是抽象父类:
package cn.itcast.test;public interface AbstructClas {//对于注解属性名为value的情况,可以不写属性名@myannotation("check")public void test();}
子类:
package cn.itcast.test;import org.junit.Test;public class ExtendClas implements AbstructClas {@Test@Overridepublic void test() {System.out.println("here is myannotation test!");try {try {if(this.getClass().getMethod("test",null).isAnnotationPresent(myannotation.class)){System.out.println("这里有指定的注解!");}else{System.out.println("没有指定的注解!");}} catch (NoSuchMethodException e) {// TODO Auto-generated catch blocke.printStackTrace();}} catch (SecurityException e) {// TODO Auto-generated catch blocke.printStackTrace();} }}
运行结果:
没有指定的注解!
但是如果注解的作用对象是类就可以被继承下来,即@Inherited(ElementType.TYPE)
对上面案例修改,1.在myannotation注解类中将@Inherited(ElementType.METHOD)修改为@Inherited(ElementType.TYPE) 2.在抽象父类中将注解的位置改加到类上面 3.在子类中将检测是否有指定注解的语句改为:this.getClass().isAnnotationPresent(myannotation.class)
另外还试验了接口上的注解能否被实现它的类继承下来,结果发现无法继承。
这里有篇文章:(CSDN网友ldh911告知)http://xiangdefei.iteye.com/blog/1044199和我探讨的相关。写到这里,我大概看了一些作者的结论,启发我考虑到方法是否被重写这一因素。
我测了一下,不改动接口中的方法,结果接口中方法上的注解也无法被继承。如果是类中的方法上的注解,在不被子类重写的情况下,果真可以被继承下来,这一点和这篇文章中结论一致。
结论:
对于使用元注解@Inherited()修饰的自定义注解。作用在类上的自定义注解可以被继承下来。作用在接口上自定义注解不能被实现它的类继承下来。
类和接口中方法上的自定义注解不能被重写/实现了其方法的子类继承(就是说,接口因为被子类实现的时候,方法必被实现,所以其方法上的自定义注解必定不能被继承。而子类如果没有重写父类的方法的话,子类就可以继承父类方法上的自定义注解)。
备注:以上结论本人都测试过,如有疏忽,敬请指教。
- 关于元注解@Inherited的探究
- 关于元注解@Inherited()再探究
- 关于java 注解中元注解Inherited的使用详解
- 关于java 注解中元注解Inherited的使用详解
- 关于java 注解中元注解Inherited的使用详解
- java注解的Inherited
- Java target retention doucmented inherited元注解
- java Inherited 注解的详解
- Java注解@Inherited的使用
- JAVA元注解@interface详解(@Target,@Documented,@Retention,@Inherited)。
- Java注解学习四:@Inherited的使用
- Java注解学习四:@Inherited的使用
- Java注解之@Inherited的使用
- Java注解之@Inherited
- JDK 5 提供的注解: Target 、Inherited 和 Documented
- Java注解之Retention、Documented、Inherited的简单使用
- JAVA 的元注解
- JAVA的元注解。
- android apk 打包
- 详解contextConfigLocation
- mmap函数
- 【MFC】按钮点击拷贝到剪切板
- spring3.0使用注解aop需要的jar包--及其流程
- 关于元注解@Inherited的探究
- u-boot(201009版)启动
- windows7/vs2008/32位程序/默认设置,new可分配最大空间
- 导出List列表中的数据到Excel文件,并提供下载
- Android 运行时找不到类:java.lang.NoClassDefFoundError:...
- 黑马程序员_02_模板方法模式
- Struts2 第一篇 Hello World
- android 程序初始化界面.. .
- UIPopoverController