1、瞭解註解及java提供的幾個基本註解
註解:相當於一種標記,加了註解就等於打上了某中標記,沒加,則等於沒有某種標記,以後, javac編譯器,開發工具和其他程序可以用反射來了解你的類及各種元素上有無何種標記,看你 有何種標記,就去幹相應的事。標記可以加在包,類,字段,方法,方法的參數以及局部變量 上。
jdk提供的註解
Deprecated
Override
SuppressWarnings
·@Deprecated: --指示應該在註釋元素(以及包含在該註釋元素中的所有程序元素)已過時。
·@Override: 表示一個方法聲明打算重寫超類中的另一個方法聲明。
·@SuppressWarnings:指示應該在註釋元素(以及包含在該註釋元素中的所有程序元素)中取消顯示指定的編譯器警告。
2、註解的定義與反射調用
註解就相當於你的一個源程序中要調用一個類,要在某個源程序中應用某個註解,要先準備好這個註解類。就像你要調用一個類一樣,首先要編寫好這個類,然後才能去調用這個類。
·自定義註解及其應用
步驟:
1、定義一個註解
2、把註解加在某個類上
3、對註解類進行相應的操作
示例:
1、定義一個註解:public @interface MyAnnotation {}
package com.zouc.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME) //用註解方式說註解保存在運行期間
public @interface MyAnnotation {
}
2、把它加在某個類上:@MyAnnotation public class AnnotationTest{}
3、用反射進行測試AnnotationTest的定義上是否有@MyAnnotation
package com.zouc.annotation;
@MyAnnotation
public class AnnotationTest {
public static void main(String[] args) {
if(AnnotationTest.class.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation annotation = (MyAnnotation) AnnotationTest.class.getAnnotation(MyAnnotation.class);
System.out.println(annotation);
}
}
}
·註解的生命週期
使用@Retention元註解可以聲明註解的生命週期,其三種取值:RetentionPolicy.SOURCE,RetentionPolicy.CLASS,RetentionPolicy.RUNTIME;分別對應:java源文件,class文件,內存中的字節碼
·註解的作用域
使用@Target指定註解的作用範圍(用於說明註解在什麼地方使用:如方法上、類上、字段上、包上等等),它是一個枚舉類型的,舉例說明:
@Target({ElementType.METHOD,ElementType.TYPE})分別對應說這個註解作用在方法上和類上。
3、爲註解增加屬性
註解中的屬性類型可以是各種基本類型、String、Class、數組、枚舉、註解
示例:
package com.zouc.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String color() default "blue"; //爲屬性指定缺省值
String value();
int[] arrayAttr() default {1,2,3}; //數組
MetaAnnotation annotationAttr() default @MetaAnnotation(value="red"); //註解
}
package com.zouc.annotation;
@MyAnnotation(color="blue",value="red",arrayAttr= {4,5},annotationAttr=@MetaAnnotation("zc"))
public class AnnotationTest {
public static void main(String[] args) {
if (AnnotationTest.class.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation annotation = (MyAnnotation)
AnnotationTest.class.getAnnotation(MyAnnotation.class);
System.out.println(annotation.color() + annotation.value());
System.out.println(annotation.arrayAttr().length);
System.out.println(annotation.annotationAttr().value());
}
}
}