Java元數據總結:Java注釋的使用和定義
元數據從metadata一詞譯來,就是“關于數據的數據”的意思。越來越的開源框架都提供了“元數據”支持了,其實也就是注釋支持。今天系統學習一下Java注釋(Java元數據)。本文內容不限于Javadoc的注釋。
1.什么是Java元數據,有什么作用?
元數據,就是“關于數據的數據”。功能也有很多啦。你可能用過Javadoc的注釋自動生成文檔。這就是元數據功能的一種。總的來說,元數據可以用來創建文檔,跟蹤代碼的依賴性,執行編譯時格式檢查,代替已有的配置文件(如Hibernate也提供了注釋配置)
注釋有3中基本類型
a.標記注釋 --沒有變量,只有名稱標識。例如 @annotation
b.單一值注釋 --在標記注釋的基礎上提供一段數據。如 @annotation(“data”)
c.完整注釋 --可以包括多個數據成員,每個數據成員由名稱和值構成。
@annotation(val1="data1",val2="data2")
2.Java的“注釋”
Java中提供3個內置注釋類型
a. Override ,只能用于方法(不能用于類,包聲明或者其他構造)
作用:可以保證編譯時候Override函數的聲明正確性
用法:@Override
public void fun(){..}
b.Deprecated 同樣只能作用與方法
作用:對不應再使用的方法進行注解
用法:@Deprecated public void fun{...} //它們說這個注釋跟函數要同一行
c.SupressWarnings 可以注釋一段代碼
作用:關閉特定的警告信息,例如你在使用泛型的時候未指定類型
用法: @SupressWarnings(value={"unchecked"})
..代碼
Java中還提供了四種元注釋,專門負責注釋其他的注釋
@Target 表示該注釋可以用于什么地方。可用的ElementType參數包括:
CONSTRUCTOR : 構造器的聲明
FIELD : 域聲明(包括enum實例)
LOCAL_VARIABLE : 局部變量聲明
METHOD : 方法聲明
PACKAGE : 包聲明
PARAMETER : 參數聲明
TYPE : 類、接口 (包括注解類型) 或enum聲明
@Retention 表示需要在什么級別保存該注釋信息。可選的RetentionPoicy參數包括:
SOURCE : 注釋將被編譯器丟掉
CLASS : 注釋在class文件中可用,但會被VM丟棄
RUNTIME : VM將在運行時也保留注釋,因此可以通過反射機制讀取注釋的信息。
@Documented 將注釋包含在JavaDoc中
@Inheried 允許子類繼承父類中的注釋。
3. 在Java中定義自己的注釋
Java語言支持一種新的類型——注釋類型(annotation type),跟普通類差不多,在類中以符號( @ )的形式注釋其他 Java 代碼
下面將通過一個簡單的例子來實現(代碼是Brett McLaughlin 的)
@interface 申明
i.簡單的注釋類型
- package com.oreilly.tiger.ch06;
- /**
- * Marker annotation to indicate that a method or class
- * is still in progress.
- */
- public @interface InProgress { }
ii.使用定制的注釋類型
- @com.oreilly.tiger.ch06.InProgress
- public void calculateInterest(float amout,float rate)
- {
- //Need to finish this method later
- }
iii.添加成員
- package com.oreilly.tiger.ch06;
- /**
- * Marker annotation to indicate that a method or class
- * is still in progress.
- */
- public @interface InProgress {
- String value();
- }
- @com.oreilly.tiger.ch06.InProgress
- @TODO("Figure out the amount of interest per month")
- //或者@TODO(value="Figure out the amount of interest per month")
- public void calculateInterest(float amount,float rate)
- {
- }
iv.設置默認值
- package com.oreilly.tiger.ch06;
- public @interface GroupTODO {
- public enum Serverity { CRITICAL,IMPORTANT,IRIVIAL,DOCMENTATION };
- Severity severity()
- default Severity.IMPORTANT;
- String item ();
- String assignedTo();
- String dateAssigned();
- }
- }
v.使用默認值
- @com.oreilly.tiger.ch06.InProgress
- @GroupTODO(
- item="Figure out the amount of interest per month",
- assignedTo = "Brett McLaughlin",
- dateAssigned = "08/04/2004"
- )
- public void calculateInterest(float amount, float rate)
- {
- //Need to finish this method later
- }
vi.改寫默認值
- @com.oreilly.tiger.ch06.InProgress
- @GroupTODO
- {
- severity = GroupTODO.Severity.DOCUMENTATION,
- item = "Need to explain how this rather unusal method works",
- assignedTo = "Jon Stevens",
- dateAssigned = "07/30/2004"
- }
這樣就對Java元數據/Java注釋進行了總結。
【編輯推薦】