Java Annotation註解,javaannotation註解
參考:Java官方文檔http://docs.oracle.com/javase/specs/jls/se7/html/jls-9.html#jls-9.6
一、註解類型:
是一種特殊類型的interface,區別在於註解聲明是 @interface
二、樣本:(Android 架構一般怎麼用註解省代碼的)
1.註解的聲明
@Retention(RetentionPolicy.RUNTIME)public @interface TestAnno {public int viewId();}
2.註解的使用
public class MainActivity extends Activity { @TestAnno(viewId = R.id.view)private View view; @Overrideprotected void onCreate(Bundle savedInstanceState) {AnnoUtil.assignView(this); }}
3.代碼中使用註解資訊(就是架構裡常做的)
public class AnnoUtil{public static void assignView(Activity context){Field[] fields = context.getClass().getDeclaredFields();for (Field field : fields) {TestAnno anno = field.getAnnotation(TestAnno.class);if (anno != null) {//為了訪問private常量,需要取消 讀取檢查field.setAccessible(true);try {field.set(context, context.findViewById(anno.viewId()));} catch (IllegalArgumentException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}}}}}
(一般架構就是這麼搞的了,這樣也確實挺省代碼的)
三、特點:
1.java的註解不可顯式聲明父類(實際上他們都繼承了Annotation類,但是你在聲明時無法使用extends 關鍵字),也無法被泛化。
2.方法:
a) 每個方法都定義了該註解中的一個元素(Each method declaration in an annotation type declaration defines an element of the annotation type)。
(擦!不看文檔我一直以為註解沒有方法,因為他用方法名稱賦值比如 @
b) 註解中的方法形參不可以有參數
c) 註解中的方法不可以拋出異常
d)方法的返回值(即註解的element)必須是如下之一: a primitive type(基礎類型:int、float等), String, Class, parameterized invocation of Class, enum, annotation,array
(parameterized invocation of Class :在java 5後java.lang.Class為泛型類,意味著他可以有型別參數,具體指Class<...>的形式,舉例: Class<? extends Formatter> value();)
e)如果方法的聲明中沒有加 default 關鍵字,則必須在使用泛型是進行賦值
d) 如果想建立架構,在運行期間通過反射調用註解,需要你的註解加上註解@Retention(RetentionPolicy.RUNTIME),否則註解可能在編譯期間就消除了。
3.如無特殊聲明,註解和interface一樣(都是靜態欄位)