自定義註解
@interface 使用 @interface 關鍵字定義註解
String value() default "";
成員變量 只有一個必須是value 默認值:defaule ""
成員變量類型是受限的,合法的類型包括原始類型及String,Class,annotation,Enumeration。
可以沒有成員變量 :稱之爲標識註解
@Target 作用域
@Target:指定被修飾的Annotation可以放置的位置(被修飾的目標)
@Target(ElementType.TYPE)
@Target(ElementType.FIELD)
@Target(ElementType.METHOD)
@Target(ElementType.PARAMETER)
@Target(ElementType.CONSTRUCTOR)
@Target(ElementType.LOCAL_VARIABLE)
@Target(ElementType.ANNOTATION_TYPE)
@Target(ElementType.PACKAGE)
@Retention(RetentionPolicy.SOURCE)
@Retention(RetentionPolicy.CLASS)
@Retention(RetentionPolicy.RUNTIME)
@Inherited 允許被子類繼承
@Documented 表示生成javadoc時會包含註解
實踐
1. 定義一個註解類
@Target({ElementType.METHOD})
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotion {
String value();
}
2. 定義一個類 在類的一個方法中加上註解
public class Demo {
@MyAnnotion("test")
public void test() {
}
}
3. 獲取註解內容
public class Test {
public static void main(String[] args) {
try {
Class<?> aClass = Class.forName("com.smile.annotion.Demo");
Method test = aClass.getMethod("test");
boolean annotationPresent = test.isAnnotationPresent(MyAnnotion.class);
if (annotationPresent){
MyAnnotion annotation = test.getAnnotation(MyAnnotion.class);
System.out.println(annotation.value());
}
} catch (ClassNotFoundException | NoSuchMethodException e) {
e.printStackTrace();
}
}
}
}