【注解Annotation】自定义注解

定义注解Annotation

使用@interface定义注解
例子:

@Retention(RetentionPolicy.RUNTIME)//通常我们自定义的Annotation都是RUNTIME
@Target(ElementType.METHOD, ElementType.FIELD) //定义注解@Report可用在方法或字段上
public @interface Report {
  int type() default 0;
}
  • 注解的参数类似于无参数的方法,可以用default设定一个默认值

元注解meta annotation

元注解是可以用来修饰其他注解的

1. @Target

用来定义Annotation能够被应用在源码的哪些位置、

  • 类/接口:ElementType.TYPE
  • 字段:ElementType.FIELD
  • 方法:ElementType.METHOD
  • 构造函数:ElementType.CONSTRUCTOR
  • 方法参数:ElementType.PARAMETER

2. @Retention

用来定义Annotation的生命周期

  • 仅编译期:RetentionPolicy.SOURCE
  • 仅class文件:RetentionPolicy.CLASS
  • 运行期:RetentionPolicy.RUNTIME

若Retention不存在,则annotation默认为class

3. @Repeatable

用来定义annotation可以重复
经过该注解修饰后,在某个类型的声明处,可以添加多个annotation

4. @Inherited

  • 用来定义子类是否可以继承父类定义的annotation
  • 仅针对 @Target(ElementType.TYPE)类型的annotation有效
  • 仅针对class的继承,对interface无效

使用自定义注解

  • 只讨论如何读取RUNTIME类型的注解
  • 反射API
    • 判断某个注解是否存在于class/field/method/constructor中: Class.isAnnotationPresent(Class) / Field.isAnnotationPresent(Class) / Method.isAnnotationPresent(Class) / Constructor.isAnnotationPresent(Class)
    • 读取Annotation: Class.getAnnotation(Class) / Field.getAnnotation(Class) / Method.getAnnotation(Class) / Constructor.getAnnotation(Class)
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容