注解
1 什么是注解(Annotation)
public class Test01 extends Object{//@Override重寫的注解@Overridepublic String toString() {return "Test01{}";}
}
2 內置注解
2.1 @Override
@Override重寫的注解
@Override
public String toString() {return "Test01{}";
}
2.2 @Deprecated
@Deprecated 不推薦程序員使用,但是可以使用,存在更好的方法.
@Deprecated
public static void test(){System.out.println("Test01");
}
2.3 @SuppressWarnings
@SuppressWarnings 鎮壓警告,平時寫代碼不建議鎮壓警告。
@SuppressWarnings("all")
public static void test02(){List list = new ArrayList();
}
3 元注解
元注解作用:負責注解其他注解。重點掌握,@Target,@Retention
3.1 定義一個注解
@interface MyAnnotation {}
3.2 @Target
@Target 表示我們的注解可以用在哪些地方
//Target注解的作用:注解自定義的interface注解
//只能在方法,類上使用
@Target({ElementType.METHOD,ElementType.TYPE})
@interface MyAnnotation {}
3.3 @Retention
@Retention用以描述注解的生命周期
SOURCE源碼級別,CLASS編譯之后,
RUNTIME運行時(用的最多)
自定義的類一般都寫RUNTIME
注解在什么階段有效
//runtime>class>source
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {}
3.4 @Documented
@Documented 表示是否將我們的注解生成在JavaDoc中。
//Documented 表示是否將我們的注解生成在JavaDoc中
@Documented
@interface MyAnnotation {}
3.5 @Inherited
@Inherited 子類可以繼承父類的注解
//Inherited 子類可以繼承父類的注解
@Inherited
@interface MyAnnotation {}
//Target注解的作用:注解自定義的interface注解
//只能在方法,類上使用
@Target({ElementType.METHOD,ElementType.TYPE})//Retention表示注解在什么階段有效
//runtime>class>source
@Retention(RetentionPolicy.RUNTIME)//Documented 表示是否將我們的注解生成在JavaDoc中
@Documented//Inherited 子類可以繼承父類的注解
@Inherited//定義一個注解
@interface MyAnnotation {}
4 自定義注解
此時并未給注解賦默認值,因此在類或方法上使用該注解時得傳入一個值。
public class Test03 {@MyAnnotation1(name = "韓立")public void test(){}
}
//自定義注解
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation1 {//注解的參數:參數類型+參數名+();String name();
}@interface MyAnnotation1 {//注解的參數:參數類型+參數名+();String name();
}
此時注解默認值為空,在類或方法上使用該注解時可不用傳入一個值。
public class Test03 {@MyAnnotation1()public void test(){}
}
//自定義注解
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation1 {//注解的參數:參數類型+參數名+();String name() default " ";
}
public class Test03 {@MyAnnotation1()public static void test(){}@MyAnnotation2(value = "hh")public static void test2(){}public static void main(String[] args) {test();}
}@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
自定義注解
@interface MyAnnotation1 {//注解的參數:參數類型+參數名+();并不是方法String name() default " ";int age() default 0;int id() default -1;//若默認值為-1,代表不存在String [] school() default {"清華"};
}@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
//自定義注解
@interface MyAnnotation2 {String value();
}
;//若默認值為-1,代表不存在
String [] school() default {“清華”};
}
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
//自定義注解
@interface MyAnnotation2 {
String value();
}