Java8新特性(六)重复注解与类型注解

本文介绍了Java8引入的新特性,包括允许使用@Repeatable注解来实现注解的重复使用,以及新增的ElementType.TYPE_PARAMETER和TYPE_USE,使得注解可以在泛型类型参数和类型使用中应用。通过示例展示了如何定义和使用这些新特性。
摘要由CSDN通过智能技术生成

一,重复注解

在java7及之前,同一个注解不能重复的使用在同一个类或方法上,如下是会报编译错误的:

在java8之后,被 @Repeatable 标注的注解是可以重复使用的,示例如下:

  1. 定义一个注解

注意使用了 @Repeatable 注解,表示可重复

@Repeatable(MyAnnotationContainer.class)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
    String value() default "aaa";
}

  1. 定义@Repeatable 需要的 MyAnnotationContainer

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotationContainer {
    MyAnnotation[] value();
}

注意:

① 字段类型是 数组类型( MyAnnotation[] )

② 字段名称要与上面一致( 此例中都叫value )

③ MyAnnotationContainer的 @Target 参数个数及值 要是 MyAnnotation 中存在的

  1. 测试类

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

被该值所修饰的注解可以作用在泛型类,泛型接口,泛型方法上。

// 声明注解
@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

表示该注解能使用在使用类型的任意语句中

// 声明类型注解

@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) {

    }

}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值