Annotations
定義annotation類型
1.public @interface xxxxx{ //以@interface 表明這是一個annotation 類型
int id(); //每個方法都是該annotation的一個element,不得有參數和拋出異常。
String syposis();//返加類型:原始類型及String Class,enums annotations 及以這些類型作爲基本類型的數組。
String engineer() default "[unassigned]";//可以設定默認值。
}
使用:
@xxxxx(
id = 33,//每個element都以","分隔。
syposis = "Enable dddd",
engineer = "xxxx" //最後結尾沒有符合。
) //一般放在public static final等限定符前面。
public static void someMethod(){ }
<!--[if !supportEmptyParas]--> <!--[endif]-->
2.沒有element 的annotation
public @interface xxNoElement{}
使用時可以省去後面的括號。
@xxNoElement() //也可以是@xxNoElement
public void someMethod(){}
<!--[if !supportEmptyParas]--> <!--[endif]-->
3.如果只有一個element 這個element的名稱必須是value.
public @interface xxOneElement{
String value();
}
使用:
@xxOneElement( value = "vvvv")
//也可以是:@xxOneElement("vvvvvv")
public Class getSomeClass(){}
<!--[if !supportEmptyParas]--> <!--[endif]-->
在定義一個annotation時也可指定該annotation使用位置(method,field constructor package等)以及應該保持多長時間。
@Retention (RetentionPolicy.RUNTIME) //CLASS,RUNTIME,SOURCE
@Target (ElementType.METHOD) //ANNOTATION_TYPE,CONSTRUCTOR,FIELD,LOCAL_VARIBALE,METHOD,PACHAGE,PARAMETER,TYPE
public @interface xxxx{
}
<!--[if !supportEmptyParas]--> <!--[endif]-->
運用@annotation
import java.lang.reflect.*;
<!--[if !supportEmptyParas]--> <!--[endif]-->
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);
}
}