java中自定义注解_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > java中自定义注解

java中自定义注解

 2018/5/7 12:56:30  一边天  程序员俱乐部  我要评论(0)
  • 摘要:java自定义注解中的三个主要注解:@Target:指示注释内容的上下文,有如下类型:/**Class,interface(includingannotationtype),orenumdeclaration*/TYPE,/**Fielddeclaration(includesenumconstants)*/FIELD,/**Methoddeclaration*/METHOD,/**Formalparameterdeclaration*/PARAMETER
  • 标签:Java 注解 自定义
java 自定义注解中的三个主要注解:

   @Target:指示注释内容的上下文,有如下类型:

    
class="java"> /** 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();
        }

    
发表评论
用户名: 匿名