@Target:指示注释内容的上下文,有如下类型:
/** Class, interface (including annotation type), or enum declaration */ TYPE, /** Field declaration (includes enum constants) */ FIELD, /** Method declaration */ METHOD, /** Formal parameter declaration */ PARAMETER, /** Constructor declaration */ CONSTRUCTOR, /** Local variable declaration */ LOCAL_VARIABLE, /** Annotation type declaration */ ANNOTATION_TYPE, /** Package declaration */ PACKAGE, /** * Type parameter declaration * * @since 1.8 */ TYPE_PARAMETER, /** * Use of a type * * @since 1.8 */ TYPE_USE
@Retention:指示注释类型的注释多长时间为保留。如果不存在保留注释注释类型声明,保留策略默认为class,有如下类型
/** * Annotations are to be discarded by the compiler. */ SOURCE, /** * Annotations are to be recorded in the class file by the compiler * but need not be retained by the VM at run time. This is the default * behavior. */ CLASS, /** * Annotations are to be recorded in the class file by the compiler and * retained by the VM at run time, so they may be read reflectively. * * @see java.lang.reflect.AnnotatedElement */ RUNTIME
@Documented:指示类型的注释要由JavaDoc记录
自定义的注解:
@Target({ElementType.FIELD,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface AnnotationTest { public boolean isAnnotation() default false; public String name() default ""; public String value () default ""; }
使用:
@AnnotationTest(name = "wangxiangyang",isAnnotation = true) public void testAnnotation(){ System.out.println("------------"); }
获取注解中的值:
try{ Method method = LuceneTest.class.getDeclaredMethod("testAnnotation"); if (method.isAnnotationPresent(AnnotationTest.class)){ AnnotationTest annotationTest = method.getAnnotation(AnnotationTest.class); System.out.println(annotationTest.isAnnotation()); System.out.println(annotationTest.name()); System.out.println(annotationTest.value()); System.out.println(annotationTest.toString()); } }catch (Exception e){ e.printStackTrace(); }