# Java8之注解新特性 **Repository Path**: fpfgitmy_admin/java8-annontation ## Basic Information - **Project Name**: Java8之注解新特性 - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2021-04-28 - **Last Updated**: 2021-04-28 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README #### JDK8注解新特性 ##### 可重复注解 1. 在`Myannotation`上声明`@Repeatable`,成员值为`MyAnnotations.class` 2. `MyAnnotation`的`Target`和`Retention`和`MyAnnotations`相同 3. 代码如下 4. `MyAnnotation`的定义 ``` package com.felixfei.study.annotations; import java.lang.annotation.*; /** * @describle 自定义注解 */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR}) @Repeatable(MyAnnotations.class) public @interface MyAnnotation { String value() default "helle"; } ``` 5. `Myannotations`的定义 ##### ``` package com.felixfei.study.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @describle */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR }) public @interface MyAnnotations { MyAnnotation[] value(); } ``` 6. 重复注解的使用方式 ``` package com.felixfei.study.test; import com.felixfei.study.annotations.MyAnnotation; /** * @describle 自定义注解,体现了扩展性 */ @MyAnnotation(value = "abc") @MyAnnotation(value = "edf") public class TestAnnotation { public static void main(String[] args) { } } ``` ##### 类型注解 + ElementType.TYPE_PARAMETER:表示该注解能写在类型变量的声明语句中(如:泛型声明) 1. 定义`MyAnnotation` ``` package com.felixfei.study.annotations; import java.lang.annotation.*; /** * @describle 自定义注解 */ @Target({ElementType.TYPE_PARAMETER}) @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { String value() default "helle"; } ``` 2. 使用注解 ``` package com.felixfei.study.test; import com.felixfei.study.annotations.MyAnnotation; /** * @describle */ // 使用注解修饰泛型的类型 public class TestAnnotation<@MyAnnotation T> { } ``` + ElementType.TYPE_USE:表示该注解能写在使用类型的任何语句中 1. 定义注解 ``` package com.felixfei.study.annotations; import java.lang.annotation.*; /** * @describle 自定义注解 */ @Target({ElementType.TYPE_USE }) @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { String value() default "helle"; } ``` 2. 使用注解 ``` package com.felixfei.study.test; import com.felixfei.study.annotations.MyAnnotation; import java.util.ArrayList; /** * @describle */ // 使用注解修饰泛型的类型 public class TestAnnotation<@MyAnnotation T> { // 修饰异常 public void show() throws @MyAnnotation RuntimeException { // 修饰泛型 ArrayList<@MyAnnotation String> objects = new ArrayList<>(); // 修饰基本类型 int num = (@MyAnnotation int) 10; } public static void main(String[] args) { } } ``` + 注意:可以通过反射获取注解,开发系统中的业务