第十五章 JDK 8 重复注解与类型注解

目录

一、重复注解的使用

1.1. 重复注解的使用步骤

1.1.1. 定义重复的注解容器注解

1.1.2. 定义一个可以重复的注解

1.1.3. 配置多个重复的注解

​编辑1.1.4. 解析得到指定注解

二、类型注解的使用

2.1. TYPE_PARAMETER的使用

2.2. TYPE_USE的使用


一、重复注解的使用

自从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 {
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值