JDK8中对于注解这块儿也有增强哦,不清楚的快来看看(建议收藏)

  最近刚好有空给大家整理下JDK8的特性,这个在实际开发中的作用也是越来越重了,本文重点讲解下注解这块的增强。

JDK8注解的增强

1.重复注解

​ 自从Java 5中引入 注解 以来,注解开始变得非常流行,并在各个框架和项目中被广泛使用。不过注解有一个很大的限

制是:在同一个地方不能多次使用同一个注解。JDK 8引入了重复注解的概念,允许在同一个地方多次使用同一个注

解。在JDK 8中使用**@Repeatable**注解定义重复注解。

1.1 定义一个重复注解的容器

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotations {
     

    MyAnnotation[] value();
}

1.2 定义一个可以重复的注解

@Repeatable(MyAnnotations.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
     
    String value();
}

1.3 配置多个重复的注解

@MyAnnotation("test1")
@MyAnnotation("test2")
@MyAnnotation("test3")
public class AnnoTest01 {
     

    @MyAnnotation("fun1")
    @MyAnnotation("fun2")
    public void test01(){
     

    }

}

1.4 解析得到指定的注解

    /**
     * 解析重复注解
     * @param args
     */
    public static void main(String[] args) throws NoSuchMethodException {
     
        // 获取类中标注的重复注解
        MyAnnotation[] annotationsByType = AnnoTest01.class.getAnnotationsByType(MyAnnotation.class);
        for (MyAnnotation myAnnotation : annotationsByType) {
     
            System.out.println(myAnnotation.value());
        }
        // 获取方法上标注的重复注解
        MyAnnotation[] test01s = AnnoTest01.class.getMethod("test01")
                .getAnnotationsByType(MyAnnotation.class);
        for (MyAnnotation test01 : test01s) {
     
            System.out.println(test01.value());
        }
    }

2.类型注解

JDK 8为@Target元注解新增了两种类型: TYPE_PARAMETER , TYPE_USE 。

  • TYPE_PARAMETER :表示该注解能写在类型参数的声明语句中。 类型参数声明如: 、
  • TYPE_USE :表示注解可以再任何用到类型的地方使用。

TYPE_PARAMETER

@Target(ElementType.TYPE_PARAMETER)
public @interface TypeParam {
     
}

使用:

public class TypeDemo01 <@TypeParam T> {
     

    public <@TypeParam K extends Object> K test01(){
     
        return null;
    }
}

TYPE_USE

@Target(ElementType.TYPE_USE)
public @interface NotNull {
     
}

使用

public class TypeUseDemo01 {
     

    public @NotNull Integer age = 10;

    public Integer sum(@NotNull Integer a,@NotNull Integer b){
     
        return a + b;
    }
}

好了~JDK8新特性这块的内容就完整的给大家整理到这儿了,如果感觉对你有帮助,欢迎点赞关注加收藏了 V_V

你可能感兴趣的:(JDK8新特性,JDK8新特性,Java,注解)