Chinaunix首页 | 论坛 | 博客
  • 博客访问: 92124
  • 博文数量: 33
  • 博客积分: 1465
  • 博客等级: 上尉
  • 技术积分: 345
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-31 13:51
文章分类

全部博文(33)

文章存档

2011年(2)

2010年(31)

我的朋友

分类: Java

2010-10-31 17:39:45

Annotation就是注释,在J2SE 5.0中,注释是以‘@注释名’在代码中存在的,例如:J2SE 5.0内置的注释:@Override、@Deprecated;有的注释还可以添加一些参数值,例 如:@SuppressWarnings(value="unchecked");对于这种只有一个参数,且参数名为value的注释,我们在使用时可以 简写为:@SuppressWarnings("unchecked")。

Annotation有三类,一类是标准的Annotation,而且号称“即拆即用”(out of thebox),也就是直接可以用,是包含在java.lang中的系统自带的。第二类是自己定义的annotation,第三类则是 metaannotation(元注释)。使用annotation时,前面要加“@”
(一)第一类annotation。有三个,分别是override,deprecated和SupressWarning。前两个功能和javadoc中是一样的,为了注明某个方法或者字段是否为重载的或者废弃的。而第三个则是用来控制编译选项的,叫做“抑制警告”。
1. @Override注释能实现编译时检查,你可以为你的方法添加该注释,以声明该方法是用于覆盖父类中的方法。如果该方法不是覆盖父类的方法,将会在编译 时报错。例如我们为某类重写toString()方法却写成了tostring(),并且我们为该方法添加了@Override注释;代码如下:
Java代码
  1. package com.gelc.annotation.demo.basic;  
  2. public class OverrideDemo {  
  3.     // @Override  
  4.     public String tostring() {  
  5.         return super.toString();  
  6.     }  
  7. }  

在编译时,则会提示以下错误信息:
OverrideTest.java:5: 方法未覆盖其父类的方法
        @Override

         ^
1 错误

    就像示例演示的那样,该注释一大好处就是可以在编译时帮我们捕获部分编译错误,但又有多少编程人员愿意为每个覆盖父类的方法添加该注释呢?这个只有靠编程人员自己进行取舍了。
2. @Deprecated的作用是对不应该在使用的方法添加注释,当编程人员使用这些方法时,将会在编译时显示提示信息,它与javadoc里的 @deprecated标记有相同的功能,准确的说,它还不如javadoc @deprecated,因为它不支持参数,使用@Deprecated的示例代码示例如下:
Java代码
  1. package com.gelc.annotation.demo.basic;  
  2. public class DeprecatedDemo {  
  3.     public static void main(String[] args) {  
  4.         // DeprecatedClass.DeprecatedMethod();  
  5.     }  
  6. }  
  7. class DeprecatedClass {  
  8.     @Deprecated  
  9.     public static void DeprecatedMethod() {  
  10.         // TODO  
  11.     }  
  12. }  
    编译时,会得到以下提示:
注意:DeprecatedDemo.java 使用或覆盖了已过时的 API。
注意:要了解详细信息,请使用 -Xlint:deprecation 重新编译。
    如果在编译时添加-Xlint:deprecation参数,我们能更清楚的看到该警告的详细信息,如下:
DeprecatedDemo.java:6: 警告:[deprecation] SomeClass 中的 DeprecatedMethod() 已
过时
                SomeClass.DeprecatedMethod();
                         ^
1 警告

    通过上面的示例,你已经掌握到了如何使用@Deprecated,但你理解到@Deprecated与@deprecated的区别了吗?你可以简单的理解为:@Deprecated是为了编译时检查,而@deprecated是为了生成文档的需要,各尽其责。
3. SupressWarning需要一个参数,语法如下:
   @SupressWarning(value={"uncheck"})
这个注释只作用于他所注释的方法或者类,而不是javac那样对整个源文件起作用。其参数如下:

参数             语义
deprecation    使用了过时的类或方法时的警告
unchecked      执行了未检查的转换时的警告,例如当使用集合时没有用泛型 (Generics) 来指定集合保存的类型
fallthrough    当 Switch 程序块直接通往下一种情况而没有 Break 时的警告
path           在类路径、源文件路径等中有不存在的路径时的警告
serial          当在可序列化的类上缺少 serialVersionUID 定义时的警告
finally         任何 finally 子句不能正常完成时的警告
all             关于以上所有情况的警告

例如:
          
Java代码
  1. @SuppressWarnings("unchecked")  
  2.     @Override  
  3.     public String execute() throws Exception  
  4.     {  
  5.         Map request = (Map) ActionContext.getContext().get("request");  
  6.         request.put("list", service.findAll());  
  7.         return SUCCESS;  
  8.     }  

(二)自己定义annotation。annotation的定义采用interface的形式(隐含的表示annotation其实是一个特殊的接口)
   public @interface EXAMPLE{
    String value()
   }
  以接口的形式定义annotation的名字,以方法的形式定义annotation的member(member好像是类里面的公有字段,或者称为annotation的属性,属性可以是一个也可以多个),用的时候如下
   @EXAMPLE("happy time")
   public void testmethod(){}
  把happy time作为“value”这个member的值。
  还有比较复杂的用法,比如在EXAMPLE的里面加上Enum的声明,然后让你的member值只能是Enum中限定的值,等等。
例如:
Java代码
  1. public class AnnotationTest {  
  2.     @NewAnnotation("Just a Test.")  
  3.     public static void main(String[] args) {  
  4.         sayHello();  
  5.         sayHelloWithDefaultFontColor();  
  6.         sayHelloWithRedFontColor();  
  7.     }  
  8.     @NewAnnotation("Hello NUMEN.")  
  9.     public static void sayHello() {  
  10.         //do something  
  11.     }  
  12.     @Greeting(name="NUMEN", content="Hello")  
  13.     public static void sayHelloWithDefaultFontColor() {  
  14.         // do something  
  15.     }  
  16.     @Greeting(name="NUMEN", content="Hello", fontColor=Greeting.FontColor.RED )  
  17.     public static void sayHelloWithRedFontColor() {  
  18.         // do something  
  19.     }  
  20. }  

(三)metaannotation。元注释又叫“注释的注释”,顾名思义,是用来定义annotation的一组annotation,用在自定义annotation时。就像所谓的metadata(元信息),即“信息的信息”。元注释有四种,
一是target,即这个注释可以被用在哪些地方。
二是documented,即这个注释能否出现在生成的javadoc中。
三是Retention,决定编译器和JVM如何处理这个注释。
四是Inherited,即这个注释能否被继承下去,就是说,当被注释的类继承以后,他的子类还会不会有这个注释。
   @Inherited
   @Documentd
   public @interface EXAMPLE{}
这段代码的意思是:这个EXAMPLE注释要出现在生成的javadoc中,而且当EXAMPLE修饰一个类时,它的子类同样会得到EXAMPLE,也就是“继承”的意思了。
限定注释使用范围

   当我们的自定义注释不断的增多也比较复杂时,就会导致有些开发人员使用错误,主要表现在不该使用该注释的地方使用。为此,Java提供了一个 ElementType枚举类型来控制每个注释的使用范围,比如说某些注释只能用于普通方法,而不能用于构造函数等。下面是Java定义的 ElementType枚举:

Java代码
  1. package java.lang.annotation;  
  2.   
  3. public enum ElementType {  
  4.   TYPE,         // Class, interface, or enum (but not annotation)  
  5.   FIELD,        // Field (including enumerated values)  
  6.   METHOD,       // Method (does not include constructors)  
  7.   PARAMETER,        // Method parameter  
  8.   CONSTRUCTOR,      // Constructor  
  9.   LOCAL_VARIABLE,   // Local variable or catch clause  
  10.   ANNOTATION_TYPE,  // Annotation Types (meta-annotations)  
  11.   PACKAGE       // Java package  
  12. }  

    下面我们来修改Greeting注释,为之添加限定范围的语句,这里我们称它为目标(Target)使用方法也很简单,如下:
Java代码
  1. package com.gelc.annotation.demo.customize;  
  2.   
  3. @Target( { ElementType.METHOD, ElementType.CONSTRUCTOR })  
  4. public @interface Greeting {  
  5.     public enum FontColor {  
  6.         RED, GREEN, BLUE  
  7.     };  
  8.     String name();  
  9.     String content();  
  10.     FontColor fontColor() default FontColor.BLUE;  
  11. }  

正如上面代码所展示的,我们只允许Greeting注释标注在普通方法和构造函数上,使用在包申明、类名等时,会提示错误信息。
注释保持性策略
    在Java编译器编译时,它会识别在源代码里添加的注释是否还会保留,这就是RetentionPolicy。下面是Java定义的RetentionPolicy枚举:

编译器的处理有三种策略:

Ø         将注释保留在编译后的类文件中,并在第一次加载类时读取它

Ø         将注释保留在编译后的类文件中,但是在运行时忽略它

Ø         按照规定使用注释,但是并不将它保留到编译后的类文件中
Java代码
  1. package java.lang.annotation;  
  2.   
  3. public enum RetentionPolicy {  
  4.   SOURCE,       // Annotation is discarded by the compiler  
  5.   CLASS,        // Annotation is stored in the class file, but ignored by the VM  
  6.   RUNTIME       // Annotation is stored in the class file and read by the VM  
  7. }  
RetentionPolicy的使用方法与ElementType类似,简单代码示例如下:
Java代码
  1. package com.gelc.annotation.demo.customize;  
  2.   
  3. import java.lang.annotation.ElementType;  
  4. import java.lang.annotation.Retention;  
  5. import java.lang.annotation.RetentionPolicy;  
  6. import java.lang.annotation.Target;  
  7.   
  8. @Retention(RetentionPolicy.RUNTIME)  
  9. @Target( { ElementType.METHOD, ElementType.CONSTRUCTOR })  
  10. public @interface Greeting {  
  11.     public enum FontColor {  
  12.         RED, GREEN, BLUE  
  13.     };  
  14.     String name();  
  15.     String content();  
  16.     FontColor fontColor() default FontColor.BLUE;  
  17. }  

文档化功能

    Java提供的Documented元注释跟Javadoc的作用是差不多的,其实它存在的好处是开发人员可以定制Javadoc不支持的文档属性,并在开发中应用。它的使用跟前两个也是一样的,简单代码示例如下:
Java代码
  1. package com.gelc.annotation.demo.customize;  
  2.   
  3. import java.lang.annotation.Documented;  
  4. import java.lang.annotation.ElementType;  
  5. import java.lang.annotation.Retention;  
  6. import java.lang.annotation.RetentionPolicy;  
  7. import java.lang.annotation.Target;  
  8.   
  9. @Documented  
  10. @Retention(RetentionPolicy.RUNTIME)  
  11. @Target( { ElementType.METHOD, ElementType.CONSTRUCTOR })  
  12. public @interface Greeting {  
  13.     public enum FontColor {  
  14.         RED, GREEN, BLUE  
  15.    };  
  16.    
  17.     String name();  
  18.     String content();  
  19.     FontColor fontColor() default FontColor.BLUE;  
  20. }  
值得大家注意的是,如果你要使用@Documented元注释,你就得为该注释设置RetentionPolicy.RUNTIME保持性策略。为什么这样做,应该比较容易理解,这里就不提了。

标注继承

继承应该是Java提供的最复杂的一个元注释了,它的作用是控制注释是否会影响到子类,简单代码示例如下:
Java代码
  1. package com.gelc.annotation.demo.customize;  
  2.   
  3. import java.lang.annotation.Documented;  
  4. import java.lang.annotation.ElementType;  
  5. import java.lang.annotation.Inherited;  
  6. import java.lang.annotation.Retention;  
  7. import java.lang.annotation.RetentionPolicy;  
  8. import java.lang.annotation.Target;  
  9.   
  10. @Inherited  
  11. @Documented  
  12. @Retention(RetentionPolicy.RUNTIME)  
  13. @Target( { ElementType.METHOD, ElementType.CONSTRUCTOR })  
  14. public @interface Greeting {  
  15.     public enum FontColor {  
  16.       RED, GREEN, BLUE  
  17.     };  
  18.     String name();  
  19.     String content();  
  20.     FontColor fontColor() default FontColor.BLUE;  
  21. }  

读取注释信息

    当我们想读取某个注释信息时,我们是在运行时通过反射来实现的,如果你对元注释还有点印象,那你应该记得我们需要将保持性策略设置为RUNTIME,也就 是说只有注释标记了@Retention(RetentionPolicy.RUNTIME)的,我们才能通过反射来获得相关信息,下面的例子我们将沿用 前面几篇文章中出现的代码,并实现读取AnnotationTest类所有方法标记的注释并打印到控制台。好了,我们来看看是如何实现的吧:
Java代码
  1. package com.gelc.annotation.demo.reflect;  
  2.   
  3. import java.lang.annotation.Annotation;  
  4. import java.lang.reflect.Method;  
  5.   
  6. public class AnnotationIntro {  
  7.     public static void main(String[] args) throws Exception {  
  8.         Method[] methods = Class.forName(  
  9.                 "com.gelc.annotation.demo.customize.AnnotationTest")  
  10.                 .getDeclaredMethods();  
  11.         Annotation[] annotations;  
  12.   
  13.         for (Method method : methods) {  
  14.             annotations = method.getAnnotations();  
  15.             for (Annotation annotation : annotations) {  
  16.                 System.out.println(method.getName() + " : "  
  17.                         + annotation.annotationType().getName());  
  18.             }  
  19.         }  
  20.     }  

阅读(865) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-10-31 19:16:50

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com