在Java中设计和使用自己的注解(转载)

来源:互联网 发布:mac子弹头brave试色 编辑:程序博客网 时间:2024/06/05 19:00

我们用过JDK给我们提供的 @Override @Deprecated @SuppressWarning 注解 ,这些注解是JDK给我们提供的,我们只是在用别人写好的东西,那么我们是否可以自己写注解呢?当然是可以的。

我们写的注解包括三个环节:

1、 注解的声明,也就是注解类的定义。

形式如下 @interface 来进行注解的声明。

  1. package me.test;     

  2.  

  3. import java.lang.annotation.* ;//导入注解包中所有注解  

  4.  

  5. @Retention(RetentionPolicy.RUNTIME)   //解释如下  

  6.  

  7. @Target(ElementType.TYPE)//解释如下  

  8.  

  9. public @interface MyAnnotation               

  10. {   

  11.  

  12. }  

  13.  

  14. @Retention(RetentionPolicy.RUNTIME)  

指定了注解保留的周期,注解的生命周期有是三个,RetentionPolicy 枚举的三个值代表了三个声明周期,默认是CLASS。


枚举常量摘要CLASS
          编译器将把注释记录在类文件中,但在运行时 VM 不需要保留注释。RUNTIME
          编译器将把注释记录在类文件中,在运行时 VM 将保留注释,因此可以反射性地读取。SOURCE
          编译器要丢弃的注释。


@Target(ElementType.TYPE)

这个标识注解应该标在那里ElementType的几个枚举值就代表了,注解应该写在的位置。


CONSTRUCTOR
          构造方法声明FIELD
          字段声明(包括枚举常量)LOCAL_VARIABLE
          局部变量声明METHOD
          方法声明PACKAGE
          包声明PARAMETER
          参数声明TYPE
          类、接口(包括注释类型)或枚举声明


2、 使用了注解的类或者方法。

  1. @MyAnnotation 

  2. class  A  

  3. {  

3、 利用反射来操作注解,详细见代码。

Class类有一个方法:


<A extends Annotation> 
A   getAnnotation(Class<A> annotationClass)


这个方法接受一个注解的字节码参数 ,然后返回这个类所标识的注解对象 ,因为我们标识了一个注解就相当于产生了一个注解对象 。


booleanisAnnotationPresent(Class<? extends Annotation> annotationClass)


这个方法判断一个类是否被注解所标识。

下面是代码示例:

MyAnnotationTest.java中

  1. package me.test;  

  2. import java.lang.annotation.Annotation;  

  3. @MyAnnotation 

  4. public class MyAnnotationTest  

  5. {   

  6.  

  7.     public static void main(String []args)  

  8.     {  

  9.      if(MyAnnotationTest.class.isAnnotationPresent( MyAnnotation.class))  

  10.      {  

  11.        MyAnnotation an=(MyAnnotation)MyAnnotationTest.class.getAnnotation(MyAnnotation.class) ;  

  12.        System.out.println(an.toString());  

  13.      }  

  14.     }  

MyAnnotation.java中

  1. package me.test;  

  2. import java.lang.annotation.ElementType;  

  3. import java.lang.annotation.Retention;  

  4. import java.lang.annotation.RetentionPolicy;  

  5. import java.lang.annotation.Target;  

  6. @Retention(RetentionPolicy.RUNTIME)  

  7. @Target(ElementType.TYPE)  

  8. public @interface MyAnnotation  

  9. {   

  10.  

0 0
原创粉丝点击