多重注解
- 在注解前使用 @Repeatable 允许同一类型的注解多次使用;
- 是 JDK 1.8 新增的功能之一;
1. 定义注解
- 放置一组具体的 NewAnno 注解,在 NewAnno 注解前使用 @Repeatable,允许同一类型的注解可以多次使用;
import java.lang.annotation.Repeatable;
@interface NewAnnos {
NewAnno[] value();
}
@Repeatable(NewAnnos.class)
@interface NewAnno {
String value();
}
2. 使用多重注解
a. 方式 1
import java.lang.annotation.Repeatable;
@interface NewAnnos {
NewAnno[] value();
}
@Repeatable(NewAnnos.class)
@interface NewAnno {
String value();
}
@NewAnnos({@NewAnno("NewAnno"), @NewAnno("NewAnno")})
class Test {
}
b. 方式 2
- Java编译器会隐式地定义 @NewAnnos 注解,所以可以直接使用多重注解;
import java.lang.annotation.Repeatable;
@interface NewAnnos {
NewAnno[] value();
}
@Repeatable(NewAnnos.class)
@interface NewAnno {
String value();
}
@NewAnno("NewAnno")
@NewAnno("NewAnno")
class Test2 {
}