JDK8新特性之重复注解

自从java5中引入注解以来,注解的使用就变得非常普遍,并在各个框架和项目中广泛使用,不过注解在同一个地方不能多次使用。为此,JDK8引入了重复注解的概念,允许在同一个地方使用同一个注解。在JDK8中使用@Repeatable注解定义重复注解。

重复注解的使用步骤:

1、定义重复注解容器注解

@Retention(RetentionPolicy.RUNTIME)
@Interface Mytests{
    MyTest[] value;
}

2、定义一个可以重复的注解

@Retention(RetentionPolicy.RUNTIME)
@Repeatable(MyTests.class)
@interface MyTest{
    String value();
}

3、配置多个重复的注解

@MyTest("tbc")
@MyTest("tba")
@MyTest("tbb")
public class Demo1{
    @MyTest("mbc")
    @MyTest("mba")
    publiv void test() throws NoSuchMethodException{
        
    }
}

4、解析得到指定注解

案例:

//1、定义注解的容器
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
    MyAnnotation[] value();
}
//2、定义重复注解
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(MyAnno.class)
@interface MyAnnotation {
    String value();
}

//使用注解
@MyAnnotation("类上的注解1111")
@MyAnnotation("类上的注解2222")
@MyAnnotation("类上的注解3333")
public class AnnotationTest {
    @Test
    @MyAnnotation("方法上的注解1111")
    @MyAnnotation("方法上的注解22222")
    public void test() throws NoSuchMethodException {
        //得到类上的注解
        MyAnnotation[] tests  = AnnotationTest.class.getAnnotationsByType(MyAnnotation.class);
        for (MyAnnotation ma :tests) {
            System.out.println(ma.value());//得到类上注解
        }

        //得到方法上的注解
        MyAnnotation[] methods = AnnotationTest.class.getMethod("test").getAnnotationsByType(MyAnnotation.class);
        for (MyAnnotation method : methods) {
            System.out.println(method.value());//得到方法上注解
        }
    }
}

类型注解的使用:

JDK8为@Target元注解新增了2种类型:TYPE_PARAMETER、TYPE_USE.

TYPE_PARAMETER:表示该注解可以写在类型参数的声明语句中,类型参数声明如:<T>

TYPE_USE:表示该注解可以在任何用到类型的地方使用

TYPE_PARAMETER的使用:

@Target(ElementType.TYPE_PARAMETER)
@interface TyptParam{
    
}

public class ParameterTest<@TyptParam>{
    public static void main(String[] args){
        
    }
    public <@TyptParam E> void test(String a){
    }
}

TYPE_USE的使用:

@Target(ElementType.TYPE_USE)
@interface NotNull{
    
}
public class TypeTest<@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){
        
    }
    
}

小结

通过@Repeatable元注解可以定义可重复注解, TYPE_PARAMETER 可以让注解放在泛型上, TYPE_USE 可以让注解放在类型的前面

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值