標籤:rate ado 產生 方式 int retention 傳回值 run 檢查
註解中繼資料分為4部分分別為Target,Documented,Inherited,Retention:
Target>指定被註解的註解僅僅能使用在某個類型上;ElementType指定其類型:能夠為方法
欄位,類,傳回值等等;
聲明:
/** * @author Lean @date:2014-10-13 */@Target(ElementType.METHOD)public @interface WorkInProgress {}
應用:
/** * @author Lean @date:2014-10-13 */public class AnnotationSample {//當在欄位中使用時:The annotation @WorkInProgress is disallowed for this location//@WorkInProgressprivate int age;@WorkInProgresspublic static boolean doSomeThing() {// TODO Auto-generated method stubreturn false;}}
Retention>設定註解可見度;使用到RetentionPolicy枚舉
RetentionPolicy.SOURCE>>編譯器可見,但對.class檔案和執行時不可見;
RetentionPolicy.CLASS>>預設工具可見,對.class檔案可見,但執行不可見;
RetentionPolicy.RUNTIME>>執行時可見;不會被.class檔案所知,在執行時告訴JVM的值;
下面範例為執行時內省檢查,當一個元註解須要多個限定值的時,必須使用{}和逗號隔開,
如@Target({ElementType.METHOD,ElementType.TYPE})
/** * @author Lean @date:2014-10-13 */@WorkInProgresspublic class AnnotationSample {private int age;@WorkInProgresspublic static boolean doSomeThing() {// TODO Auto-generated method stubreturn false;}public static void main(String[] args) {AnnotationSample obj=new AnnotationSample();Class clazz=obj.getClass();WorkInProgress progress=(WorkInProgress) clazz.getAnnotation(WorkInProgress.class);System.out.println(clazz.getName());if (clazz.isAnnotationPresent(WorkInProgress.class)) {System.out.println("class Annotationed WorkInProgress!");}Method[] methods=clazz.getMethods();for (Method method : methods) {if (method.isAnnotationPresent(WorkInProgress.class)) {System.out.println("method Annotationed WorkInProgress!");}}}}@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD,ElementType.TYPE})@interface WorkInProgress {}
Documented>為加入註解的類書寫文檔,編譯執行後執行javadoc的dos命令.就可以在該命令列
位置看到所產生的文檔.
Inherited>當對某個類進行註解的時候,希望對繼承他的子類也進行註解.預設情況下
沒有使用該@Inherited註解方式,系統會覺得子類不須要繼承該功能,例如以下:
/** * @author Lean @date:2014-10-13 */@WorkInProgresspublic class AnnotationSample {public static void main(String[] args) throws IllegalAccessException {AnnotationSample obj=new AnnotationSample();Class clazz=obj.getClass();if (clazz.isAnnotationPresent(WorkInProgress.class)) {System.out.println("class Annotationed WorkInProgress!");}Class childClass=AnnotationChildClass.class;if (childClass.isAnnotationPresent(WorkInProgress.class)) {System.out.println("child class Annotationed WorkInProgress!");}}}@Inherited@Documented@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD,ElementType.TYPE})@interface WorkInProgress {}class AnnotationChildClass extends AnnotationSample{}
JAVA進階-註解