注解 @Target 用法
生活随笔
收集整理的這篇文章主要介紹了
注解 @Target 用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點擊跳轉到教程。
@Target:
@Target說明了Annotation所修飾的對象范圍:Annotation可被用于 packages、types(類、接口、枚舉、Annotation類型)、類型成員(方法、構造方法、成員變量、枚舉值)、方法參數和本地變量(如循環變量、catch參數)。在Annotation類型的聲明中使用了target可更加明晰其修飾的目標。
作用:用于描述注解的使用范圍(即:被描述的注解可以用在什么地方)
取值(ElementType)有
public?enum?ElementType {/**用于描述類、接口(包括注解類型) 或enum聲明 Class, interface (including annotation type), or enum declaration */TYPE,/** 用于描述域 Field declaration (includes enum constants) */FIELD,/**用于描述方法 Method declaration */METHOD,/**用于描述參數 Formal parameter declaration */PARAMETER,/**用于描述構造器 Constructor declaration */CONSTRUCTOR,/**用于描述局部變量 Local variable declaration */LOCAL_VARIABLE,/** Annotation type declaration */ANNOTATION_TYPE,/**用于描述包 Package declaration */PACKAGE,/*** 用來標注類型參數 Type parameter declaration* @since 1.8*/TYPE_PARAMETER,/***能標注任何類型名稱 Use of a type* @since 1.8*/TYPE_USE?
| 1 | ElementType.TYPE_PARAMETER(Type parameter declaration) 用來標注類型參數, 栗子如下: |
ElementType.TYPE_USE(Use of a type) 能標注任何類型名稱,包括上面這個(ElementType.TYPE_PARAMETER的),栗子如下:
public?class?TestTypeUse {@Target(ElementType.TYPE_USE)@Retention(RetentionPolicy.RUNTIME)public?@interface?TypeUseAnnotation {}public?static?@TypeUseAnnotation?class?TypeUseClass<@TypeUseAnnotation?T>?extends?@TypeUseAnnotation?Object {public?void?foo(@TypeUseAnnotation?T t)?throws?@TypeUseAnnotation?Exception {}}// 如下注解的使用都是合法的@SuppressWarnings({?"rawtypes",?"unused",?"resource"?})public?static?void?main(String[] args)?throws?Exception {TypeUseClass<@TypeUseAnnotation?String> typeUseClass =?new?@TypeUseAnnotation?TypeUseClass<>();typeUseClass.foo("");List<@TypeUseAnnotation?Comparable> list1 =?new?ArrayList<>();List<??extends?Comparable> list2 =?new?ArrayList<@TypeUseAnnotation?Comparable>();@TypeUseAnnotation?String text = (@TypeUseAnnotation?String)new?Object();java.util.?@TypeUseAnnotation?Scanner console =?new?java.util.@TypeUseAnnotation?Scanner(System.in);}}?
總結
以上是生活随笔為你收集整理的注解 @Target 用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: QT 调用 DLL 的三种方法
- 下一篇: Qt中的模态对话框和非模态对话框