lang dot annoation - JiyangM/spring GitHub Wiki

  • @Documented 表示使用该注解的元素应被javadoc或类似工具文档化.如果一个类型声明添加了 Documented 注解,那么它的注解会成为被注解元素的公共API的一部分。

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
}
  • @Inherited 表示一个注解类型会被自动继承。只能用在类上。被该注解标注的注解类 子类继承时,将继承父类的注解。

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
}
  • @Repeatable 表示课重复的注解,比如再角色系统中,一个方法可以被多个角色使用。

@Repeatable(value = Roles.class)
	public static @interface Role {
		String name() default "doctor";
	}
 
	@Target(ElementType.TYPE)
	@Retention(RetentionPolicy.RUNTIME)
	public static @interface Roles {
		Role[] value();
	}
	
	@Role(name = "doctor")
	@Role(name = "who")
	public static class RepeatAnn{
		
	}
	
	@Roles({@Role(name="doctor"),
			@Role(name="who")})
	public static class Annotations{
		
	}

  • @Retention注解,表示注解保留时间长短。有些注解仅存在于源码中,在编译过程中被丢弃;另一些会被一起编译进class文件中。编译在class文件中的注解可能会被虚拟机忽略,也可能会在class文件被装载时读取使用。其取值在java.lang.annotation.RetentionPolicy定义,包括:

    • SOURCE:在源文件中有效,编译过程中会被忽略
    • CLASS:随源文件一起编译在class文件中,运行时忽略
    • RUNTIME:在运行时有效

回到上面的例子,其 Retention 取值为 RetentionPolicy.RUNTIME,说明该注解将被保留至程序运行期间。事实上,当处于运行期间时,注解处理器可以通过反射机制,获取到该注解的属性值,从而做一些运行时的逻辑处理。

  • @Target 表示注解修饰的对象范围,取值在java.lang.annotation.ElementType定义,包括:

ANNOTATION_TYPE:用于描述注解类型 CONSTRUCTOR:用于描述构造器 FIELD:用于描述域 LOCAL_VARIABLE:用于描述局部变量 METHOD:用于描述方法 PACKAGE:用于描述包 PARAMETER:用于描述方法变量 TYPE:用于描述类、接口或enum类型 TYPE_PARAMETER:用于Type的声明式前 TYPE_USE:用于所有使用Type的地方(如泛型,类型转换)