註解是jdk1.5的新特性。
Annotation
1.@override
2.@supreesedwaring
3.@deprectaed
註解是指加了一個標記
註解可以加在包,類,變量,方法上面
爲註解添加屬性,
創建註解:
public @interface Annotation
{
String color();//屬性
String age();default("sd")//默認值
}
使用:
@Annotation(color="red")
註解的類返回類型可以是八種基本類型,亦可以是String,枚舉,註解還可以是上述類型的數組
下面是一個定義註解的實例
- package Test_annotation;
- import java.lang.annotation.Documented;
- import java.lang.annotation.Inherited;
- import java.lang.annotation.Retention;
- import java.lang.annotation.Target;
- import java.lang.annotation.ElementType;
- import java.lang.annotation.RetentionPolicy;
- /*
- * 元註解@Target,@Retention,@Documented,@Inherited
- *
- * @Target 表示該註解用於什麼地方,可能的 ElemenetType 參數包括:
- * ElemenetType.CONSTRUCTOR 構造器聲明
- * ElemenetType.FIELD 域聲明(包括 enum 實例)
- * ElemenetType.LOCAL_VARIABLE 局部變量聲明
- * ElemenetType.METHOD 方法聲明
- * ElemenetType.PACKAGE 包聲明
- * ElemenetType.PARAMETER 參數聲明
- * ElemenetType.TYPE 類,接口(包括註解類型)或enum聲明
- *
- * @Retention 表示在什麼級別保存該註解信息。可選的 RetentionPolicy 參數包括:
- * RetentionPolicy.SOURCE 註解將被編譯器丟棄
- * RetentionPolicy.CLASS 註解在class文件中可用,但會被VM丟棄
- * RetentionPolicy.RUNTIME VM將在運行期也保留註釋,因此可以通過反射機制讀取註解的信息。
- *
- * @Documented 將此註解包含在 javadoc 中
- *
- * @Inherited 允許子類繼承父類中的註解
- *
- */
- @Target(ElementType.METHOD)
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- @Inherited
- /*
- * 定義註解 Test
- * 註解中含有兩個元素 id 和 description
- * description 元素 有默認值 "no description"
- */
- public @interface Test {
- public int id();
- public String description() default "no description";
- }
下面是一個使用註解 和 解析註解的實例
- package Test_annotation;
- import java.lang.reflect.Method;
- public class Test_1 {
- /*
- * 被註解的三個方法
- */
- @Test(id = 1, description = "hello method_1")
- public void method_1() {
- }
- @Test(id = 2)
- public void method_2() {
- }
- @Test(id = 3, description = "last method")
- public void method_3() {
- }
- /*
- * 解析註解,將Test_1類 所有被註解方法 的信息打印出來
- */
- public static void main(String[] args) {
- Method[] methods = Test_1.class.getDeclaredMethods();
- for (Method method : methods) {
- /*
- * 判斷方法中是否有指定註解類型的註解
- */
- boolean hasAnnotation = method.isAnnotationPresent(Test.class);
- if (hasAnnotation) {
- /*
- * 根據註解類型返回方法的指定類型註解
- */
- Test annotation = method.getAnnotation(Test.class);
- System.out.println("Test( method = " + method.getName()
- + " , id = " + annotation.id() + " , description = "
- + annotation.description() + " )");
- }
- }
- }
- }