Annotation分為兩種,第一種為系統內置注解,第二種為自定義注解。
系統內置注解:例如@Override,@Dprecated
自定義注解:定義格式為?
【public】 @interface Annotation名稱{
????數據類型 變量名稱();
}
其中數據類型和變量自定義,不作限制。
Retention和RetentionPolicy
在Annotation中,可以使用Retention定義個Annotation的保存范圍,此Annotation的定義如下:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Meaning { FormItemType value() ; //設置為枚舉類型
}
RetentionPolicy表示保存范圍,主要有
ElementType表示使用類型,主要有
想要注解變得有意義,需要結合反射使用。
例:
package com.itmyhome; import java.lang.annotation.Annotation;
import java.lang.reflect.Method; class Demo{ @SuppressWarnings("unchecked") @Deprecated @Override public String toString(){ return "hello"; }
} public class T { public static void main(String[] args) throws Exception{ Class<?> c = Class.forName("com.itmyhome.Demo"); Method mt = c.getMethod("toString"); //找到toString方法 Annotation an[] = mt.getAnnotations(); //取得全部的Annotation for(Annotation a:an){ System.out.println(a); } }
}