Java定义注释类型
示例
注释类型用定义@interface。参数的定义类似于常规接口的方法。
@interface MyAnnotation {
String param1();
boolean param2();
int[] param3(); //数组参数
}默认值
@interface MyAnnotation {
String param1() default "someValue";
boolean param2() default true;
int[] param3() default {};
}元注释
元批注是可以应用于批注类型的批注。特殊的预定义元注释定义了注释类型的使用方式。
@目标
该@Target元注释限制注解可以应用到的类型。
@Target(ElementType.METHOD)
@interface MyAnnotation {
//此注释只能应用于方法
}可以使用数组符号添加多个值,例如@Target({ElementType.FIELD,ElementType.TYPE})
可用值
@Retention(RetentionPolicy.RUNTIME) @interface MyAnnotation
@MyAnnotation
public MyClass() {}@XmlAttribute private int count;
for (@LoopVariable int i = 0; i < 100; i++) {
@Unused
String resultVariable;
}@Deprecated package very.old;
@XmlElement
public int getCount() {...}public Rectangle(
@NamedArg("width") double width,
@NamedArg("height") double height) {
...
}@XmlRootElement
public class Report {}public <@MyAnnotation T> void f(T t) {}Object o = "42"; String s = (@MyAnnotation String) o;
@保留
该@Retention元注释定义了在应用程序编译过程或执行注释知名度。默认情况下,注释包含在.class文件中,但在运行时不可见。为了使注释在运行时可访问,RetentionPolicy.RUNTIME必须在该注释上进行设置。
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
//可以在运行时通过反射来访问此批注
}可用值
@记录
该@Documented元注释是用来标记注释,其使用应通过API文档生成javadoc的一样被记录。它没有值。使用@Documented,所有使用注释的类都将在其生成的文档页面上列出它。没有@Documented,就无法查看文档中哪些类使用了注释。
@遗传
该@Inherited元注释是有关被应用于类的注释。它没有值。将注释标记为@Inherited会更改注释查询的工作方式。
对于非继承的注释,查询仅检查正在检查的类。
对于继承的注释,查询还将(递归)检查超类链,直到找到注释的实例。
请注意,仅查询超类:将附加到类层次结构中接口的任何注释。
@可重复
在@RepeatableJava中8.加入元注释这表明注释的多个实例可以连接到注释的目标。此元注释没有值。