当前位置:网站首页>補:注解(Annotation)
補:注解(Annotation)
2022-04-23 04:27:00 【我已經學會了沉默】
主要內容:
- 注解(Annotation)概述
- 常見的Annotation示例
- 自定義Annotation
- JDK中的元注解
- 利用反射獲取注解信息(在反射部分涉及)
- JDK 8中注解的新特性
目錄
常見的注解示例
使用Annotation時要在其前面增加@符號,並把Annotation當成一個修飾符使用。用於修飾它支持的程序元素
示例一:生成文檔相關的注解
@author:標明開發該類模塊的作者,多個作者之間使用,分割
@version:標明該類模塊的版本
@see:參考轉向,也就是相關主題
@since:從哪個版本開始增加的
@param:對方法中某參數的說明,如果沒有參數就不能寫
@return對方法返回值的說明,如果方法的返回值類型是void就不能寫
@exception:對方法可能拋出的异常進行說明,如果方法沒有用throws顯式拋出的异常就不能寫其中
注意:
@param @return和@exception這三個標記都是只用於方法的。
@param的格式要求:@param形參名形參類型形參說明
@return的格式要求:@return返回值類型返回值說明
@exception的格式要求:exception异常類型异常說明
@param和@exception可以並列多個
示例二:在編譯時進行格式檢查(JDK內置的三個基本注解)
@Override:限定重寫父類方法,該注解只能用於方法
@Deprecated:用於錶示所修飾的元素(類,方法等)已過時。通常是因為所修飾的結構危險或存在更好的選擇
@SuppressWarnings:抑制編譯器警告
示例三:跟踪代碼依賴性,實現替代配置文件功能
Servlet3.o提供了注解(annotation),使得不再需要在web.xml文件中進行Servlet的部署。
自定義注解:
參照@SupperWarning
- 注解聲明為:@interface
- 內部定義成員,通常使用value錶示
- 可以指定成員的默認值,使用default定義
- 如果自定義注解沒有成員,錶明是一個標識作用。
定義新的Annotation類型使用@interface關鍵字
自定義注解自動繼承了java.lang.annotation.Annotation接口
Annotation的成員變量在 Annotation定義中以無參數方法的形式來聲明。其方法名和返回值定義了該成員的名字和類型。我們稱為配置參數。類型只能是八種基本數據類型、String類型、class類型、enum類型、Annotation類型、以上所有類型的數組。
可以在定義Annotation的成員變量時為其指定初始值,指定成員變量的初始值可使用default關鍵字
如果只有一個參數成員,建議使用參數名為value
如果定義的注解含有配置參數,那麼使用時必須指定參數值,除非它有默認值。格式是“參數名=參數值”,如果只有一個參數成員,且名稱為value,可以省略“value=”
沒有成員定義的Annotation稱為標記;包含成員變量的 Annotation稱為元數據Annotation
注意:自定義注解必須配上注解的信息處理流程才有意義。
自定義注解通過都會指明兩個元注解: Retention(生命周期). Target(作用域)
自定義注解示例
public @interface MyAnnotation {
String [] value();
}
指定默認值
public @interface MyAnnotation {
String [] value() default "hello";
}
@Override 沒有成員
public @interface Override {
}
元注解
對現有的注解進行注解的注解
JDK的元Annotation用於修飾其他Annotation定義
JDK5.0提供了4個標准的meta-annotation類型,分別是:
- Retention:指定所修飾的Annotation的生命周期:SOURCE\CLASS(默認行為)\RUNTIME 只有聲明為RUNTIME生命周期的注解,才能通過反射獲取。
- Target:用於指定被修飾的Annotation能用於修飾哪些程序元素
- 以下兩個使用較少
- Documented:錶示所修飾的注解在被javadoc解析時,保留下來。
- Inherited:被它修飾的Annotation將具有繼承性。

@Retention
只能用於修飾一個Annotation定義,用於指定該Annotation的生命周期, @Rentention包含一個RetentionPolicy類型的成員變量,使用
@Rentention時必須為該value成員變量指定值:
- RetentionPolicy.SOURCE:在源文件中有效(即源文件保留),編譯器直接丟弃這種策略的注釋
- RetentionPolicy.CLASS:在class文件中有效(即class保留),當運行Java程序時,JVM不會保留注解。這是默認值
- RetentionPolicy.RUNTIME:在運行時有效(即運行時保留),當運行Java程序時,JVM會保留注釋。程序可以通過反射獲取該注釋。
例如@SuppressWarnings()源碼中
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
/**
* The set of warnings that are to be suppressed by the compiler in the
* annotated element. Duplicate names are permitted. The second and
* successive occurrences of a name are ignored. The presence of
* unrecognized warning names is <i>not</i> an error: Compilers must
* ignore any warning names they do not recognize. They are, however,
* free to emit a warning if an annotation contains an unrecognized
* warning name.
*
* <p> The string {@code "unchecked"} is used to suppress
* unchecked warnings. Compiler vendors should document the
* additional warning names they support in conjunction with this
* annotation type. They are encouraged to cooperate to ensure
* that the same names work across multiple compilers.
* @return the set of warnings to be suppressed
*/
String[] value();
}
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE,
/**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
*/
CLASS,
/**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}
@Target
用於修飾Annotation定義,用於指定被修飾的Annotation能用於修飾哪些程序元素。@Target也包含一個名為value的成員變量。
| 取值 | 取值 | ||
|---|---|---|---|
| CONSTRUCTOR | 用於描述構造器 | PACKAGE | 用於描述包 |
| FLELD | 用於描述域 | PARAMETRE | 用於描述參數 |
| LOCAL_VARIABLE | 用於描述局部變量 | TYPE | 用於描述類、接口(包括注解類型)或enum聲明 |
| METHOD | 用於描述方法 |
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
/**
* Returns an array of the kinds of elements an annotation type
* can be applied to.
* @return an array of the kinds of elements an annotation type
* can be applied to
*/
ElementType[] value();
}
public enum ElementType {
/** 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
}
@Documented
用於指定被該元Annotation修飾的Annotation類將被javadoc工具提取成文檔。默認情况下,javadoc是不包括注解的。
定義為Documented的注解必須設置Retention值為RUNTIME。
@Inherited
被它修飾的Annotation將具有繼承性。如果某個類使用了被@lnherited修飾的Annotation,則其子類將自動具有該注解。
- 比如:如果把標有@Inherited注解的自定義的注解標注在類級別上,子類則可以繼承父類類級別的注解
- 實際應用中,使用較少
jdk 8中注解的新特性:
可重複注解
@MyAnnotation(value = "hello")
@MyAnnotation(value = "hi")
class Person {
private String name;
private int age;}
直接這樣寫會報錯
解决辦法:
在jdk8以前
1.將注解裏的值聲明為注解類型的數組
public @interface MyAnnotations {
MyAnnotation[] value();
}
2.將兩個注解放入
@MyAnnotations({@MyAnnotation(value = "hello"),@MyAnnotation(value = "hi")})
class Person {
private String name;
private int age;}
在jdk8以後
在MyAnnotation上聲明@Repeatable,成員值為MyAnnotations.class
MyAnnotation的@Target和@Retention@Inherited必須和MyAnnotations相同。
@Repeatable(MyAnnotations.class)
public @interface MyAnnotation {
String [] value() default "hello";
}
public @interface MyAnnotations {
MyAnnotation[] value();
}
@MyAnnotation(value = "hello")
@MyAnnotation(value = "hi")
class Person {
private String name;
private int age;
}
類型注解
JDK1.8之後,關於元注解@Target的參數類型ElementType枚舉值多了兩 個
- TYPE_PARAMETER
- TYPE_USE
在Java 8之前,注解只能是在聲明的地方所使用,Java8開始,注解可以應用在任何地方。
- ElementType.TYPE_PARAMETER錶示該注解能寫在類型變量的聲明語句中(如:泛型聲明)
- ElementType.TYPE_USE錶示該注解能鄒在使用類型的任何語句中。
版权声明
本文为[我已經學會了沉默]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230426360531.html
边栏推荐
- 阿里十年技术专家联合打造“最新”Jetpack Compose项目实战演练(附Demo)
- Matlab minimalist configuration of vscode configuration
- 创下国产手机在海外市场销量最高纪录的小米,重新关注国内市场
- 【BIM入门实战】Revit建筑墙体:构造、包络、叠层图文详解
- Shopping mall for transportation tools based on PHP
- [echart] démarrer avec echart
- Operating skills of spot gold_ Wave estimation curve
- RC低通滤波器的逆系统
- 【BIM+GIS】ArcGIS Pro2. 8 how to open Revit model, Bim and GIS integration?
- How to regulate intestinal flora? Introduction to common natural substances, probiotics and prebiotics
猜你喜欢

Express middleware ① (use of Middleware)

Chlamydia infection -- causes, symptoms, treatment and Prevention

MYSQL查询至少连续n天登录的用户

减治思想——二分查找详细总结

Cortex-M3寄存器组、汇编语言与C语言的接口介绍

STM32单片机ADC规则组多通道转换-DMA模式

Does China Mobile earn 285 million a day? In fact, 5g is difficult to bring more profits, so where is the money?

Thought of reducing Governance -- detailed summary of binary search

一个函数秒杀2Sum 3Sum 4Sum问题

兼容NSR20F30NXT5G的小体积肖特基二极管
随机推荐
HMS Core Discovery第14期回顾长文|纵享丝滑剪辑,释放视频创作力
io.Platform.packageRoot; // ignore: deprecated_member_use
[BIM introduction practice] Revit building wall: detailed picture and text explanation of structure, envelope and lamination
matlab讀取多張fig圖然後合並為一張圖(子圖的形式)
LabVIEW 小端序和大端序区别
UDP协议与TCP协议
为什么推荐你学嵌入式
The whole process of connecting the newly created unbutu system virtual machine with xshell and xftp
【BIM入门实战】Revit建筑墙体:构造、包络、叠层图文详解
QT program integration easyplayer RTSP streaming media player screen flicker what is the reason?
AWS EKS添加集群用户或IAM角色
顺序表的基本操作
matlab读取多张fig图然后合并为一张图(子图的形式)
Shopping mall for transportation tools based on PHP
【ICCV 2019】MAP-VAE:Multi-Angle Point Cloud-VAE: Unsupervised Feature Learning for 3D Point Clouds..
TreeSet after class exercises
Operating skills of spot gold_ Wave estimation curve
使用大华设备开发行AI人流量统计出现时间不正确的原因分析
【时序】基于 TCN 的用于序列建模的通用卷积和循环网络的经验评估
Mysql出现2013 Lost connection to MySQL server during query