比如有一個註解:
package testUseAnnotation;
//(1)
public @interface MyAnnotation {
String value() default "註解的默認值";
}
下面是註解的使用類
package testUseAnnotation;
import java.lang.annotation.Annotation;
@MyAnnotation(value = "註解的應用值")
public class TestUseAnnotation {
public static void main(String[] args) {
MyAnnotation mAnnotation = TestUseAnnotation.class.getAnnotation(MyAnnotation.class);
System.out.println( mAnnotation.value());//(2)
}
}
運行上面的TestUseAnnotation類是不能在代碼(2)處輸出mAnnotation.value值的;會報錯
因爲需要在代碼(1)處加上
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
完整的註解寫法如下: