目录
一、重复注解的使用
自从Java 5中引入 注解 以来,注解开始变得非常流行,并在各个框架和项目中被广泛使用。不过注解有一个很大的限
制是:在同一个地方不能多次使用同一个注解。JDK 8引入了重复注解的概念,允许在同一个地方多次使用同一个注解。在JDK 8中使用@Repeatable注解定义重复注解。
1.1. 重复注解的使用步骤
1.1.1. 定义重复的注解容器注解

1.1.2. 定义一个可以重复的注解
1.1.3. 配置多个重复的注解
1.1.4. 解析得到指定注解
@MyTest("tbc")
@MyTest("tba")
@MyTest("tba")
class Annotation1 {
@MyTest("mbc")
@MyTest("mba")
public void test() throws NoSuchMethodException {
// 4.解析得到类上的指定注解
MyTest[] tests = Annotation1.class.getAnnotationsByType(MyTest.class);
for (MyTest test : tests) {
System.out.println(test.value());
}
// 得到方法上的指定注解
Annotation[] tests1 =
Annotation1.class.getMethod("test").getAnnotationsByType(MyTest.class);
for (Annotation annotation : tests1) {
System.out.println("annotation = " + annotation);
}
}
}
@Retention(RetentionPolicy.RUNTIME)
@interface MyTests {
MyTest[] value();
}
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(MyTests.class)
@interface MyTest {
String value();
}
二、类型注解的使用
JDK 8为@Target元注解新增了两种类型: TYPE_PARAMETER , TYPE_USE 。
TYPE_PARAMETER :表示该注解能写在类型参数的声明语句中。 类型参数声明如: <T> 、
TYPE_USE :表示注解可以在任何用到类型的地方使用。
2.1. TYPE_PARAMETER的使用
package com.wzx;
import java.lang.annotation.*;
public class Test<@TyptParam T> {
public static void main( String[] args) {
}
public <@TyptParam E> void test( String a) {
}
}
@Target(ElementType.TYPE_PARAMETER)
@interface TyptParam {
}
2.2. TYPE_USE的使用
package com.wzx;
import java.lang.annotation.*;
public class Test<@TyptParam T extends String> {
private @NotNull int a = 10;
public static void main(@NotNull String[] args) {
@NotNull int x = 1;
@NotNull String s = new @NotNull String();
}
public <@TyptParam E> void test( String a) {
}
}
@Target(ElementType.TYPE_USE)
@interface NotNull {
}
@Target(ElementType.TYPE_PARAMETER)
@interface TyptParam {
}