目錄
一、定義自定義註解
//作用域
//構造方法聲明CONSTRUCTOR、字段聲明FIELD、局部變量聲明LOCAL_VARIABLE
//方法聲明METHOD、包聲明PACKAGE、參數聲明PARAMETER、類/接口TYPE
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
//生命週期
//只在源碼顯示,編譯時沒有 SOURCE;
//編譯時記錄到class中,運行時忽略 CLASS;
//運行時存在,可以通過反射讀取 RUNTIME
@Retention(RetentionPolicy.RUNTIME)
//允許子類繼承(接口不行),父類替換子類註解
@Inherited
//生成javadoc時會包含註解
@Documented
public @interface Description { //@interface定義註解
//double、float、byte、short、int、long、boolean 八種原始類型
//成員類型除八種原始類型外,還包括String,Class,Annotation,Enumeration;
//如果註解只有一個成員,則成員必須取名爲value();使用註解時,可以忽略成員名和等號
//註解可以沒有成員,沒有成員稱爲標識註解
String value(); //成員以無參無異常方式聲明
String key() default ""; //可以指定default爲成員默認值
}
二、註解類
@Test("hello type")
public class Child {
@Test("Hello method")
public void sing() {
}
}
三、解析自定義註解
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class ParseAnn {
public static void main(String[] args) {
try {
//1.使用類加載器
Class child = Class.forName("Child");
//2.找到類上面的註解
boolean isExist = child.isAnnotationPresent(Test.class);
if (isExist) {
//3.拿到註解實例
Test test = (Test) child.getAnnotation(Test.class);
System.out.println(test.value());
}
//4.找到方法上的註解
Method[] methods = child.getMethods();
for (Method method : methods) {
/**
* 方式一
*/
boolean isMExist = method.isAnnotationPresent(Test.class);
if (isMExist) {
Test methodAnnotation = method.getAnnotation(Test.class);
System.out.println(methodAnnotation.value());
}
/**
* 方式二
*/
Annotation[] annotations = method.getAnnotations();
for (Annotation annotation : annotations) {
if (annotation instanceof Test) {
System.out.println(((Test) annotation).value());
}
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}