Java元注解


一、元注解定义

注解可以描述为元数据,即一种描述数据的数据。所以,可以说注解就是源代码的元数据。
所谓元注解其主要作⽤就是负责注解其他注解,为其他注解提供了相关的解释说明。
Java中常用的元注解有@Target、@Retention 、@Documented、@Inherited和@Repeatable。

二、元注解的使用

@Target:用于指定注解的使用范围或目标

ElementType.TYPE:类、接⼝、注解、枚举
ElementType.FIELD:字段、枚举常量
ElementType.METHOD:⽅法
ElementType.PARAMETER:形式参数
ElementType.CONSTRUCTOR:构造⽅法
ElementType.LOCAL_VARIABLE:局部变量
ElementType.ANNOTATION_TYPE:注解
ElementType.PACKAGE:包
ElementType.TYPE_PARAMETER:类型参数
ElementType.TYPE_USE:类型使⽤

@Retention:用于指定注解的生命周期

⽤于指定注解的保留策略
RetentionPolicy.SOURCE:注解只保留在源码中,在编译时会被编译器丢弃
RetentionPolicy.CLASS:(默认的保留策略) 注解会被保留在Class⽂件中,但不会被加载到虚拟机中,运⾏时⽆法获得
RetentionPolicy.RUNTIME:注解会被保留在Class⽂件中,且会被加载到虚拟机中,可以在运⾏时获得

@Documented:⽤于将注解包含在javadoc中

默认情况下,javadoc是不包括注解的,但如果使⽤了@Documented注解,则相关注解类型信息会被包含在⽣成的⽂档中;Documented是一个标记注解,没有成员。

@Inherited:用于指明父类注解会被子类继承得到

该注解是一个标记注解,阐述了某个被标注的类型是被继承的

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface ParentAnnotation {
    String key();
    String value();
}
@ParentAnnotation(key ="key", value ="value")
publicclass Parent {
}
publicclass Son extends Parent {
	publicstaticvoidmain(String[] args){
	   Annotation[] annotations = Son.class.getAnnotations();
	// [@com.ParentAnnotation(key=key, value=value)]
	   System.out.println(Arrays.toString(annotations));
	}
}

@Repeatable:用于声明标记的注解为可重复类型注解,可以在同⼀个地方多次使用

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(RepeatableAnnotation.class)
public @interface TestAnnotation {
    String key();
    String value();
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface RepeatableAnnotation {
    TestAnnotation[]value();
}
@TestAnnotation(key ="key1", value ="value1")
@TestAnnotation(key ="key2", value ="value2")
publicclass Test {
	publicstaticvoidmain(String[] args){
		RepeatableAnnotation annotation = Test.class.getAnnotation(RepeatableAnnotation.class);
	   	TestAnnotation[] testAnnotations = annotation.value();
		for(TestAnnotation testAnnotation : testAnnotations){
		// @com.TestAnnotation(key=key1, value=value1)
		// @com.TestAnnotation(key=key2, value=value2)
	   	System.out.println(testAnnotation);
		}
	}
}

参考:
Java-五种元注解详解

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值