-
CLASS:在class文件中有效(即class保留),不会添加载到JVM中
-
RUNTIME:在运行时有效(即运行时保留),这个和我们常用的加载是一致的,运行时会加载到JVM中,一般通过反射可获取到,一般这个是我们常用的。
@Retention(RetentionPolicy.RUNTIME)//在使用该注解其,只能选择其中一种属性,不能定义多个
public @interface RetentionTest {
}
@Documented
@Documented
用于描述其它类型的annotation应该被作为被标注的程序成员的公共API。
如下代码
@Documented //添加文档注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationTest {
}
@Inherited:
@Inherited
元注解是一个标记注解, @Inherited
阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited
修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited //添加继承注解
public @interface AnnotationTest {
}
@Repeatable
这个是在java8添加的注解特性,@Repeatable
的值表示可重复注释类型的包含注释类型。
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Repeatables {
RepeatablesTest[] value();
}
@Repeatable(Repeatables.class)
public @interface RepeatablesTest {
String value() default “哈哈哈”;
}
例子
==
我们简单的介绍了注解的常用的5个注解元,解下来我们通过例子来实现注解。
代码如下,根据上面的提示我们进行测试。
在看例子之前我们先来了解一下常用的几个方法。
-
Class.getAnnotations() 获取所有的注解,包括自己声明的以及继承的
-
Cla