Java Annotation入门

摘要:
本文针对java初学者或者annotation初次使用者全面地说明了annotation的使用方法、定义方式、分类。初学者可以通过以上的说明制作简单的annotation程序,但是对于一些高级的annotation应用(例如使用自定义annotation生成javabean映射xml文件)还需要进一步的研究和探讨。涉及到深入annotation的内容,作者将在后文《Java Annotation高级应用》中谈到。

同时,annotation运行存在两种方式:运行时、编译时。上文中讨论的都是在运行时的annotation应用,但在编译时的annotation应用还没有涉及,

一、为什么使用Annotation:

在JAVA应用中,我们常遇到一些需要使用模版代码。例如,为了编写一个JAX-RPC web service,我们必须提供一对接口和实现作为模版代码。如果使用annotation对远程访问的方法代码进行修饰的话,这个模版就能够使用工具自动生成。
另外,一些API需要使用与程序代码同时维护的附属文件。例如,JavaBeans需要一个BeanInfo Class与一个Bean同时使用/维护,而EJB则同样需要一个部署描述符。此时在程序中使用annotation来维护这些附属文件的信息将十分便利而且减少了错误。

二、Annotation工作方式:

在5.0版之前的Java平台已经具有了一些ad hoc annotation机制。比如,使用transient修饰符来标识一个成员变量在序列化子系统中应被忽略。而@deprecated这个javadoc tag也是一个ad hoc annotation用来说明一个方法已过时。从Java5.0版发布以来,5.0平台提供了一个正式的annotation功能:允许开发者定义、使用自己的annoatation类型。此功能由一个定义annotation类型的语法和一个描述annotation声明的语法,读取annotaion的API,一个使用annotation修饰的class文件,一个annotation处理工具(apt)组成。
annotation并不直接影响代码语义,但是它能够工作的方式被看作类似程序的工具或者类库,它会反过来对正在运行的程序语义有所影响。annotation可以从源文件、class文件或者以在运行时反射的多种方式被读取。
当然annotation在某种程度上使javadoc tag更加完整。一般情况下,如果这个标记对java文档产生影响或者用于生成java文档的话,它应该作为一个javadoc tag;否则将作为一个annotation。

三、Annotation使用方法:

1。类型声明方式:
通常,应用程序并不是必须定义annotation类型,但是定义annotation类型并非难事。Annotation类型声明于一般的接口声明极为类似,区别只在于它在interface关键字前面使用“@”符号。
annotation类型的每个方法声明定义了一个annotation类型成员,但方法声明不必有参数或者异常声明;方法返回值的类型被限制在以下的范围:primitives、String、Class、enums、annotation和前面类型的数组;方法可以有默认值。

下面是一个简单的annotation类型声明:
清单1:

   
Java代码   收藏代码
  1. /** 
  2.      * Describes the Request-For-Enhancement(RFE) that led 
  3.      * to the presence of the annotated API element. 
  4.      */  
  5.     public @interface RequestForEnhancement {  
  6.         int      id();  
  7.         String synopsis();  
  8.         String engineer() default "[unassigned]";   
  9.         String date();      default "[unimplemented]";   
  10.     }  


代码中只定义了一个annotation类型RequestForEnhancement。

2。修饰方法的annotation声明方式:
annotation是一种修饰符,能够如其它修饰符(如public、static、final)一般使用。习惯用法是annotaions用在其它的修饰符前面。annotations由“@+annotation类型+带有括号的成员-值列表”组成。这些成员的值必须是编译时常量(即在运行时不变)。

A:下面是一个使用了RequestForEnhancement annotation的方法声明:
清单2:

   
Java代码   收藏代码
  1. @RequestForEnhancement(  
  2.         id         = 2868724,  
  3.         synopsis = "Enable time-travel",  
  4.         engineer = "Mr. Peabody",  
  5.         date       = "4/1/3007"  
  6.     )  
  7.     public static void travelThroughTime(Date destination) { ... }  


B:当声明一个没有成员的annotation类型声明时,可使用以下方式:
清单3:

Java代码   收藏代码
  1. /** 
  2.   * Indicates that the specification of the annotated API element 
  3.   * is preliminary and subject to change. 
  4.   */  
  5.  public @interface Preliminary { }  


作为上面没有成员的annotation类型声明的简写方式:
清单4:
Java代码   收藏代码
  1. @Preliminary public class TimeTravel { ... }  



C:如果在annotations中只有唯一一个成员,则该成员应命名为value:
清单5:

    
Java代码   收藏代码
  1. /** 
  2.       * Associates a copyright notice with the annotated API element. 
  3.       */  
  4.      public @interface Copyright {  
  5.          String value();  
  6.      }  



更为方便的是对于具有唯一成员且成员名为value的annotation(如上文),在其使用时可以忽略掉成员名和赋值号(=):
清单6:

   
Java代码   收藏代码
  1. @Copyright("2002 Yoyodyne Propulsion Systems")  
  2.     public class OscillationOverthruster { ... }  

3。一个使用实例:
结合上面所讲的,我们在这里建立一个简单的基于annotation测试框架。首先我们需要一个annotation类型来表示某个方法是一个应该被测试工具运行的测试方法。
清单7:

    
Java代码   收藏代码
  1. import java.lang.annotation.*;  
  2.   
  3.      /** 
  4.       * Indicates that the annotated method is a test method. 
  5.       * This annotation should be used only on parameterless static methods. 
  6.       */  
  7.      @Retention(RetentionPolicy.RUNTIME)  
  8.      @Target(ElementType.METHOD)  
  9.      public @interface Test { }  


值得注意的是annotaion类型声明是可以标注自己的,这样的annotation被称为“meta-annotations”。

在上面的代码中,@Retention(RetentionPolicy.RUNTIME)这个meta-annotation表示了此类型的annotation将被虚拟机保留使其能够在运行时通过反射被读取。而@Target(ElementType.METHOD)表示此类型的annotation只能用于修饰方法声明。

下面是一个简单的程序,其中部分方法被上面的annotation所标注:
清单8:
Java代码   收藏代码
  1.       public class Foo {  
  2.           @Test public static void m1() { }  
  3.           public static void m2() { }  
  4.           @Test public static void m3() {  
  5.               throw new RuntimeException("Boom");  
  6.           }  
  7.           public static void m4() { }  
  8.           @Test public static void m5() { }  
  9.           public static void m6() { }  
  10.           @Test public static void m7() {  
  11.               throw new RuntimeException("Crash");  
  12.           }  
  13.           public static void m8() { }  
  14.       }  
  15.   
  16. Here is the testing tool:  
  17.   
  18.       import java.lang.reflect.*;  
  19.   
  20.       public class RunTests {  
  21.          public static void main(String[] args) throws Exception {  
  22.             int passed = 0, failed = 0;  
  23.             for (Method m : Class.forName(args[0]).getMethods()) {  
  24.                if (m.isAnnotationPresent(Test.class)) {  
  25.                   try {  
  26.                      m.invoke(null);  
  27.                      passed++;  
  28.                   } catch (Throwable ex) {  
  29.                      System.out.printf("Test %s failed: %s %n", m, ex.getCause());  
  30.                      failed++;  
  31.                   }  
  32.                }  
  33.             }  
  34.             System.out.printf("Passed: %d, Failed %d%n", passed, failed);  
  35.          }  
  36.       }  


这个程序从命令行参数中取出类名,并且遍历此类的所有方法,尝试调用其中被上面的测试annotation类型标注过的方法。在此过程中为了找出哪些方法被annotation类型标注过,需要使用反射的方式执行此查询。如果在调用方法时抛出异常,此方法被认为已经失败,并打印一个失败报告。最后,打印运行通过/失败的方法数量。
下面文字表示了如何运行这个基于annotation的测试工具:

清单9:
Java代码   收藏代码
  1. $ java RunTests Foo  
  2. Test public static void Foo.m3() failed: java.lang.RuntimeException: Boom   
  3. Test public static void Foo.m7() failed: java.lang.RuntimeException: Crash   
  4. Passed: 2, Failed 2  


四、Annotation分类:

根据annotation的使用方法和用途主要分为以下几类:

1。内建Annotation——Java5.0版在java语法中经常用到的内建Annotation:
@Deprecated用于修饰已经过时的方法;
@Override用于修饰此方法覆盖了父类的方法(而非重载);
@SuppressWarnings用于通知java编译器禁止特定的编译警告。

下面代码展示了内建Annotation类型的用法:
清单10:
Java代码   收藏代码
  1. package com.bjinfotech.practice.annotation;  
  2.   
  3. /** 
  4.  * 演示如何使用java5内建的annotation 
  5.  * 参考资料: 
  6.  * http://java.sun.com/docs/books/tutorial/java/javaOO/annotations.html 
  7.  * http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html 
  8.  * http://mindprod.com/jgloss/annotations.html 
  9.  * @author cleverpig 
  10.  * 
  11.  */  
  12. import java.util.List;  
  13.   
  14. public class UsingBuiltInAnnotation {  
  15.           //食物类  
  16.           class Food{}  
  17.           //干草类  
  18.           class Hay extends Food{}  
  19.           //动物类  
  20.           class Animal{  
  21.                   Food getFood(){  
  22.                           return null;  
  23.                   }  
  24.                   //使用Annotation声明Deprecated方法  
  25.                   @Deprecated  
  26.                   void deprecatedMethod(){  
  27.                   }  
  28.           }  
  29.           //马类-继承动物类  
  30.           class Horse extends Animal{  
  31.                   //使用Annotation声明覆盖方法  
  32.                   @Override  
  33.                   Hay getFood(){  
  34.                           return new Hay();  
  35.                   }  
  36.                   //使用Annotation声明禁止警告  
  37.                   @SuppressWarnings({"deprecation","unchecked"})  
  38.                   void callDeprecatedMethod(List horseGroup){  
  39.                           Animal an=new Animal();  
  40.                           an.deprecatedMethod();  
  41.                           horseGroup.add(an);  
  42.                   }  
  43.           }  
  44. }  


2。开发者自定义Annotation:由开发者自定义Annotation类型。
下面是一个使用annotation进行方法测试的sample:

AnnotationDefineForTestFunction类型定义如下:
清单11:
Java代码   收藏代码
  1. package com.bjinfotech.practice.annotation;  
  2.   
  3. import java.lang.annotation.*;  
  4. /** 
  5.  * 定义annotation 
  6.  * @author cleverpig 
  7.  * 
  8.  */  
  9. //加载在VM中,在运行时进行映射  
  10. @Retention(RetentionPolicy.RUNTIME)  
  11. //限定此annotation只能标示方法  
  12. @Target(ElementType.METHOD)  
  13. public @interface AnnotationDefineForTestFunction{}  


测试annotation的代码如下:

清单12:
Java代码   收藏代码
  1. package com.bjinfotech.practice.annotation;  
  2.   
  3. import java.lang.reflect.*;  
  4.   
  5. /** 
  6.  * 一个实例程序应用前面定义的Annotation:AnnotationDefineForTestFunction 
  7.  * @author cleverpig 
  8.  * 
  9.  */  
  10. public class UsingAnnotation {  
  11.           @AnnotationDefineForTestFunction public static void method01(){}  
  12.           
  13.           public static void method02(){}  
  14.           
  15.           @AnnotationDefineForTestFunction public static void method03(){  
  16.                   throw new RuntimeException("method03");  
  17.           }  
  18.           
  19.           public static void method04(){  
  20.                   throw new RuntimeException("method04");  
  21.           }  
  22.           
  23.           public static void main(String[] argv) throws Exception{  
  24.                   int passed = 0, failed = 0;  
  25.                   //被检测的类名  
  26.                   String className="com.bjinfotech.practice.annotation.UsingAnnotation";  
  27.                   //逐个检查此类的方法,当其方法使用annotation声明时调用此方法  
  28.               for (Method m : Class.forName(className).getMethods()) {  
  29.                  if (m.isAnnotationPresent(AnnotationDefineForTestFunction.class)) {  
  30.                     try {  
  31.                        m.invoke(null);  
  32.                        passed++;  
  33.                     } catch (Throwable ex) {  
  34.                        System.out.printf("测试 %s 失败: %s %n", m, ex.getCause());  
  35.                        failed++;  
  36.                     }  
  37.                  }  
  38.               }  
  39.               System.out.printf("测试结果: 通过: %d, 失败: %d%n", passed, failed);  
  40.           }  
  41. }  



3。使用第三方开发的Annotation类型
这也是开发人员所常常用到的一种方式。比如我们在使用Hibernate3.0时就可以利用Annotation生成数据表映射配置文件,而不必使用Xdoclet。

五、总结:

1。前面的文字说明了annotation的使用方法、定义方式、分类。初学者可以通过以上的说明制作简单的annotation程序,但是对于一些高级的annotation应用(例如使用自定义annotation生成javabean映射xml文件)还需要进一步的研究和探讨。

2。同时,annotation运行存在两种方式:运行时、编译时。上文中讨论的都是在运行时的annotation应用,但在编译时的annotation应用还没有涉及,因为编译时的annotation要使用annotation processing tool。

涉及以上2方面的深入内容,作者将在后文《Java Annotation高级应用》中谈到。

六、参考资源:
·Matrix-Java开发者社区: http://www.matrix.org.cn
· http://java.sun.com/docs/books/tutorial/java/javaOO/annotations.html
· http://java.sun.com/j2se/1.5.0/docs/guide/apt/GettingStarted.html
· http://java.sun.com/j2se/1.5.0/docs/guide/apt/GettingStarted.html
· http://java.sun.com/j2se/1.5.0/docs/guide/apt/GettingStarted.html
·作者的Blog: http://blog.matrix.org.cn/page/cleverpig
                          --摘自《Java Annotation 入门》
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值