上面一下1和2的源文件,它們都使用了@Documented,@Documented的目的就是讓這一個Annotation類型的信息能夠顯示在javaAPI說明文檔上;沒有添加的話,使用javadoc生成API文檔的時候就會找不到這一個類型生成的信息.
另外一點,假如需要把Annotation的數據繼續給子類,那么就會用到@Inherited這一個Annotation類型.
package lighter.javaeye.com;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Description {
String value();
}
說明:所有的Annotation會自動繼續java.lang.annotation這一個接口,所以不能再去繼續別的類或是接口.
最重要的一點,Annotation類型里面的參數該怎么設定:
第一,只能用public或默認(default)這兩個訪問權修飾.例如,String value();這里把方法設為defaul默認類型.
第二,參數成員只能用基本類型byte,short,char,int,long,float,double,boolean八種基本數據類型和String,Enum,Class,annotations等數據類型,以及這一些類型的數組.例如,String value();這里的參數成員就為String.
第三,假如只有一個參數成員,最好把參數名稱設為"value",后加小括號.例:上面的例子就只有一個參數成員.
2、Name.java
代碼
package lighter.javaeye.com;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//注重這里的@Target與@Description里的不同,參數成員也不同
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Name {
String originate();
String community();
}
3、JavaEyer.java
代碼
package lighter.javaeye.com;
@Description("javaeye,做最棒的軟件開發交流社區")
public class JavaEyer {
@Name(originate="創始人:robbin",community="javaEye")
public String getName()
{
return null;
}
@Name(originate="創始人:江南白衣",community="springside")
public String getName2()
{
return "借用兩位的id一用,寫這一個例子,請見諒!";
}
}
4、最后,寫一個可以運行提取JavaEyer信息的類TestAnnotation
代碼
package lighter.javaeye.com;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
public class TestAnnotation {
/**
* author lighter
* 說明:具體關天Annotation的API的用法請參見javaDoc文檔
*/
public static void main(String[] args) throws Exception {
String CLASS_NAME = "lighter.javaeye.com.JavaEyer";
Class test = Class.forName(CLASS_NAME);
Method[] method = test.getMethods();
boolean flag = test.isAnnotationPresent(Description.class);
if(flag)
{
Description des = (Description)test.getAnnotation(Description.class);
System.out.println("描述:"+des.value());
System.out.println("-----------------");
}
//把JavaEyer這一類有利用到@Name的全部方法保存到Set中去
Set<Method> set = new HashSet<Method>();
for(int i=0;i<method.length;i++)
{
boolean otherFlag = method[i].isAnnotationPresent(Name.class);
if(otherFlag) set.add(method[i]);
}
for(Method m: set)
{
Name name = m.getAnnotation(Name.class);
System.out.println(name.originate());
System.out.println("創建的社區:"+name.community());
}
}
}
5、運行結果:
描述:javaeye,做最棒的軟件開發交流社區
-----------------
創始人:robbin
創建的社區:javaEye
創始人:江南白衣
創建的社區:springside