一,重复注解
在java7及之前,同一个注解不能重复的使用在同一个类或方法上,如下是会报编译错误的:
在java8之后,被 @Repeatable 标注的注解是可以重复使用的,示例如下:
定义一个注解
注意使用了 @Repeatable 注解,表示可重复
java">java">@Repeatable(MyAnnotationContainer.class)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
String value() default "aaa";
}
定义@Repeatable 需要的 MyAnnotationContainer
java">java">@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotationContainer {
MyAnnotation[] value();
}
注意:
① 字段类型是 数组类型( MyAnnotation[] )
② 字段名称要与上面一致( 此例中都叫value )
③ MyAnnotationContainer的 @Target 参数个数及值 要是 MyAnnotation 中存在的
测试类
java">java">public class TestAnotations {
//测试获取注解中的值
public static void main(String[] args) throws NoSuchMethodException {
Class<TestAnotations> clazz = TestAnotations.class;
Method method = clazz.getMethod("test");
MyAnnotation[] arr = method.getAnnotationsByType(MyAnnotation.class);
for(MyAnnotation item:arr){
System.out.println(item.value());
}
}
//该方法多次使用同一个注解
@MyAnnotation("xxx")
@MyAnnotation("yyy")
public void test(){
}
}
输出如下:
二,类型注解
java8为ElementType枚举增加了TYPE_PARAMETER和TYPE_USE两个枚举值:
2.1 TYPE_PARAMETER
被该值所修饰的注解可以作用在泛型类,泛型接口,泛型方法上。
java">java">// 声明注解
@Target({ ElementType.TYPE_PARAMETER})
public @interface NotNull {}
//测试注解
public class TestNotNull<@NotNull T> {
public <@NotNull T> void testT(T x) {}
}
//测试注解
public interface A<@NotNull T> {}
2.2 TYPE_USE
表示该注解能使用在使用类型的任意语句中
java">java">// 声明类型注解
@Target(ElementType.TYPE_USE)
public @interface NotNull {}
//使用类型注解
//在继承和实现的时候都使用类型注解
@NotNull
public class TestNotNull<@NotNull T> extends @NotNull HashMap<String, String> implements @NotNull Serializable {
//声明成员变量使用类型注解
@NotNull
private T t;
@NotNull
private String test;
// 方法中使用类型注解,抛异常使用类型注解
public static void main(@NotNull String[] args) throws @NotNull Exception {
// 声明局部变量使用类型注解
@NotNull
String string;
// 创建对象使用类型注解
string = new @NotNull String("小钻风");
// 强制类型转换使用类型注解
Object object = (@NotNull Object) string;
System.out.println(object);
}
@NotNull // 声明方法使用类型注解, 泛型使用类型注解
public String test(List<@NotNull String> lists) {
return "";
}
// @NotNull 返回值为空意味着没有类型返回,所以不能够使用类型注解
public void test2() {}
public <@NotNull T> void testT(@NotNull T xddf) {
}
}