Annotation註解 筆記 上半部分

[size=large][b]Annotation註解[/b][/size]
一.如何聲明Antotation
註解的聲明很象接口的聲明,只不過加上了@標示符在interface關鍵字前,在語法上需要注意:

[size=medium]1.方法聲明不可以包含任何參數或是throws關鍵字.
2.返回類型限制於:基本類型,String,Class,enums,annotations,或是他們的數組形式,方法可以包含默認值.[/size]

請看下面代碼

public @interface requestForEnhancement{
int id();
String sysnopsis();
String engineer(); default ”[unassigend]”
String date(); default ”[unimplemented]”
}

一旦你聲明瞭註解類型,那麼怎麼使用呢?
註解是一種比較特殊的類型,你可以在class,interface,enums等之前使用它,按照默認規則,請你在修飾符前使用它,請看下面代碼,它使用上面聲明的annotations.

@requestForEnhancement(
id = 2868724,
sysnopsis = ”Enable time travle”,
engineer = “Mr . Peabody”,
date = “4/1/3007”
)
public static void travelThoughTime(Date destnation){....}

註解根據參數類型可以分爲:
1.Marker Annotations(標示註解):一個沒有任何elements(元素)的註解.

public @interface Preliminary{}

2.single-valued annotations(單列註解):只包含一個元素的註解.需要注意的是,元素必須被強制聲明爲:”value”.請看下面代碼:

public @interface Copyright {String value();}

我們也許簡單寫法,請看下面代碼,無需將value寫出來.
3.文章開頭聲明的屬於multi-valued annotations ,請自己看代碼.
4.Retention Policies
註解可以包含以下三種retention策略:
[i]1.Source-file retention
Annotations with source-file retention are read by the compiler during the compilation process, but are not rendered in the generated .class files.
2.Class-file retention
This is the default retention policy. Annotations with class-file retention are read by the compiler and also retained in the generated .class files.
3.Runtime retention
Annotations with runtime retention are read by the compiler, retained in the generated .class files, and also made available at runtime. [/i]
5.我們可以在運行時來訪問註解類型:提供了2個法:getAnnotationget,Annotations方法,還有一個檢測isAnnotationsPresents,請看下面代碼:

//首先聲明一個註解
import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test{}
//上面這種在註解內部嵌套註解的形式,SUN官方文檔稱之爲meta-annotation(元數據註解)
//上面第一句話的意思是:確認在VM中保存他,以便用於反射,動態獲取.
//第二句話的意思:這個註解只可以使用在方法上.

public class foo{
@Test public static void m1(){}
public static void m2(){}
@Test public static void m3(){
throw new RuntimeException("boom");
}
@Test public static void m5() { }
public static void m6() { }
@Test public static void m7() {
throw new RuntimeException("Crash");
}
public static void m8() { }
}
//下面寫個測試類
import java.lang.reflect.*;

public class RunTests {
public static void main(String[] args) throws Exception {
int passed = 0, failed = 0;
for (Method m : Class.forName(args[0]).getMethods()) {
if (m.isAnnotationPresent(Test.class)) {
try {
m.invoke(null);
passed++;
} catch (Throwable ex) {
System.out.printf("Test %s failed: %s %n", m, ex.getCause());
failed++;
}
}
}
System.out.printf("Passed: %d, Failed %d%n", passed, failed);
}
}
//輸出結果如下
$ java RunTests Foo
Test public static void Foo.m3() failed: java.lang.RuntimeException: Boom
Test public static void Foo.m7() failed: java.lang.RuntimeException: Crash
Passed: 2, Failed 2
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章