java annotation

来源:互联网 发布:老司机的意思网络用语 编辑:程序博客网 时间:2024/05/10 22:29
一. 最常见的annotation
  • @Override:用在方法之上,用来告诉别人这一个方法是改写父类的
  • @Deprecated:建议别人不要使用旧的API的时候用的,编译的时候会用产生警告信息,可以设定在程序里的所有的元素上.
  • @SuppressWarnings:暂时把一些警告信息消息关闭
  • @Entity:表示该类是可持久化的类
 
二. 设计一个自己的Annotation
      先看代码再讲话
1. 只有一个参数的Annotation实现
 
  1. package  chb.test.annotation;  
  2. import  java.lang.annotation.Documented;  
  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. @Target (ElementType.TYPE)  
  8. @Retention (RetentionPolicy.RUNTIME)  
  9. @Documented   
  10. public   @interface  MyAnnotation1 {  
  11.         String value();  
  12. }  
 
 
2. 有两个参数的Annotation实现
 
  1. package  chb.test.annotation;  
  2. import  java.lang.annotation.Documented;  
  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. @Target (ElementType.METHOD)  
  8. @Retention (RetentionPolicy.RUNTIME)  
  9. @Documented   
  10. public   @interface  MyAnnotation2 {  
  11.         String description();  
  12.         boolean  isAnnotation();  
  13. }  
 
 
3. Annotation实验类
 
  1. package  chb.test.annotation;  
  2. @MyAnnotation1 ( "this is annotation1" )  
  3. public   class  AnnotationDemo {  
  4.         @MyAnnotation2 (description= "this is annotation2" ,isAnnotation= true )  
  5.         public   void  sayHello(){  
  6.                 System.out.println("hello world!" );  
  7.         }  
  8. }  
 
 
4.Annotation测试说明类
 
  1. package  chb.test.annotation;  
  2. import  java.lang.reflect.Method;  
  3. import  org.junit.Test;  
  4. public   class  TestAnnotation {  
  5.         @Test   
  6.         public   void  test()  throws  ClassNotFoundException, SecurityException, NoSuchMethodException{  
  7.                 Class<?> cls = Class.forName("chb.test.annotation.AnnotationDemo" );  
  8.                 boolean  flag = cls.isAnnotationPresent(MyAnnotation1. class );  
  9.                 if (flag){  
  10.                         System.out.println("判断类是annotation" );  
  11.                         MyAnnotation1 annotation1 = cls.getAnnotation(MyAnnotation1.class );  
  12.                         System.out.println(annotation1.value());  
  13.                 }  
  14.                   
  15.                 Method method = cls.getMethod("sayHello" );  
  16.                 flag = method.isAnnotationPresent(MyAnnotation2.class ) ;  
  17.                 if (flag){  
  18.                         System.out.println("判断方法也是annotation" );  
  19.                         MyAnnotation2 annotation2 = method.getAnnotation(MyAnnotation2.class );  
  20.                         System.out.println(annotation2.description()+"/t" +annotation2.isAnnotation());  
  21.                 }  
  22.         }  
  23.           
  24. }  
 
 
实验结果,控制台打出如下信息:
 
判断类是annotation
this is annotation1
判断方法也是annotation
this is annotation2     true
 
三.简介及说明
 
1. MyAnnotation1中的@Target(ElementType.TYPE)
      @Target里面的ElementType是用来指定Annotation类型可以用在哪些元素上的.例如:
       TYPE(类型)、FIELD(属性)、METHOD(方法)、PARAMETER(参数)、CONSTRUCTOR(构造函数)、LOCAL_VARIABLE(局部变量),、PACKAGE(包),其中的TYPE(类型)是指可以用在 Class,Interface,Enum和Annotation类型上。
2. MyAnnotation1中的@Retention(RetentionPolicy.RUNTIME)
      RetentionPolicy 共有三种策略,分别为:
  • SOURCE:这个Annotation类型的信息只会保留在程序源码里,源码如果经过了编译之后,Annotation的数据就会消失,并不会保留在编译好的.class文件里面
  • CLASS:这个Annotation类型的信息保留在程序源码里,同时也会保留在编译好的.class文件里面,在执行的时候,并不会把这些信息加载到JVM中。注:默认策略为CLASS类型
  • RUNTIME:表示在源码、编译好的.class文件中保留信息,在执行的时候会把这一些信息加载到JVM中去的
3. MyAnnotation1中的@Documented
目的就是将这一Annotation的信息显示在JAVA API文档上,如果没有增加@Documented的话,JAVA API文档上不会显示相关annotation信息
 
4. MyAnnotation1中的@interface
   关键字,表示该类为Annotation定义
5. MyAnnotation1中的 String value();
   表示有一个成员参数,名字为value,访问权为默认(default)修饰符,注意以下两点:
  • 访问权只能用public和默认(default)修饰
  • 参数成员只能用基本类型byte,short,char,int,long,float,double,boolean八种基本数据类型和String,Enum,Class,annotations等数据类型,以及这一些类型的数组
6.AnnotationDemo中的@MyAnnotation1("this is annotation1")
   因为MyAnnotation1只有一个参数,因此可以直接在括号中写上value值。注:如果Annotation只有一个参数,则建议最好将该参数名称定义为value
7.TestAnnotation中的cls.isAnnotationPresent(MyAnnotation1.class)
    判断该类是否使用了MyAnnotation1的注释
8. TestAnnotation中的MyAnnotation1 annotation1 = cls.getAnnotation(MyAnnotation1.class)
    返回该类针对MyAnnotation1的注释
9. TestAnnotation中的method.isAnnotationPresent(MyAnnotation2.class)
    判断该方法是否使用了MyAnnotation2的注释

转自:http://blog.csdn.net/hbcui1984/archive/2009/10/27/4735487.aspx
 
 
 

  (1) Annotation(注释)JDK5.0及以后版本引入的。它可以用于创建文档,跟踪代码中的依赖性,甚至执行基本编译时检查。注释是以‘@注释名在代码中存在的,根据注释参数的个数,我们可以将注释分为:标记注释、单值注释、完整注释三类。它们都不会直接影响到程序的语义,只是作为注释(标识)存在,我们可以通过反射机制编程实现对这些元数据的访问。另外,你可以在编译时选择代码里的注释是否只存在于源代码级,或者它也能在class文件中出现。

元数据的作用
如果要对于元数据的作用进行分类,目前还没有明确的定义,不过我们可以根据它所起的作用,大致可分为三类:

编写文档:通过代码里标识的元数据生成文档。
代码分析:通过代码里标识的元数据对代码进行分析。

编译检查:通过代码里标识的元数据让编译器能实现基本的编译检查。

基本内置注释

@Override

 

Java代码
  1. package com.iwtxokhtd.annotation;  
  2. /** 
  3.  * 测试Override注解 
  4.  * @author Administrator 
  5.  * 
  6.  */  
  7. public class OverrideDemoTest {  
  8.   
  9.     //@Override  
  10.     public String tostring(){  
  11.         return "测试注释";  
  12.     }  
  13. }  

 

 

 

@Deprecated的作用是对不应该在使用的方法添加注释,当编程人员使用这些方法时,将会在编译时显示提示信息,它与javadoc里的@deprecated标记有相同的功能,准确的说,它还不如javadoc @deprecated,因为它不支持参数,使用@Deprecated的示例代码示例如下:

 

Java代码
  1. package com.iwtxokhtd.annotation;  
  2. /** 
  3.  * 测试Deprecated注解 
  4.  * @author Administrator 
  5.  * 
  6.  */  
  7. public class DeprecatedDemoTest {  
  8.      public static void main(String[] args) {  
  9.         //使用DeprecatedClass里声明被过时的方法  
  10.          DeprecatedClass.DeprecatedMethod();  
  11.      }  
  12. }  
  13. class DeprecatedClass{  
  14.     @Deprecated  
  15.     public static void DeprecatedMethod() {       
  16.       }   
  17. }  

 

@SuppressWarnings,其参数有:

deprecation,使用了过时的类或方法时的警告

unchecked,执行了未检查的转换时的警告

fallthrough,当 Switch 程序块直接通往下一种情况而没有 Break 时的警告

path,在类路径、源文件路径等中有不存在的路径时的警告

serial,当在可序列化的类上缺少 serialVersionUID 定义时的警告

finally ,任何 finally 子句不能正常完成时的警告

all,关于以上所有情况的警告

 

Java代码
  1. package com.iwtxokhtd.annotation;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. public class SuppressWarningsDemoTest {  
  7.   
  8.     public static List list=new ArrayList();  
  9.     @SuppressWarnings("unchecked")  
  10.     public void add(String data){  
  11.         list.add(data);  
  12.     }  
  13. }  

 

(2)自定义注释

它类似于新创建一个接口类文件,但为了区分,我们需要将它声明为@interface,如下例:

  

Java代码
  1. public @interface NewAnnotation {  
  2. }  

 

使用自定义的注释类型

 

Java代码
  1. public class AnnotationTest {  
  2.     @NewAnnotation   
  3.     public static void main(String[] args) {  
  4.     }  
  5. }   

 

 

为自定义注释添加变量

 

Java代码
  1. public @interface NewAnnotation {   
  2.      String value();   
  3. }   

 

 

  

Java代码
  1. public class AnnotationTest {   
  2.      @NewAnnotation("main method")   
  3.     public static void main(String[] args) {   
  4.         saying();   
  5.     }   
  6.     @NewAnnotation(value = "say method")   
  7.      public static void saying() {  
  8.      }  
  9. }   

 

 

 

 定义一个枚举类型,然后将参数设置为该枚举类型,并赋予默认值

  

Java代码
  1. public @interface Greeting {     
  2. public enum FontColor{  
  3.        BLUE,RED,GREEN  
  4.     };  
  5.     String name();  
  6.     FontColor fontColor() default FontColor.RED;}    
  7. }  

 

 

这里有两种选择,其实变数也就是在赋予默认值的参数上,我们可以选择使用该默认值,也可以重新设置一个值来替换默认值

 

Java代码
  1. @NewAnnonation("main method")  
  2.     public static void main(String[] args) {  
  3.             saying();     
  4.             sayHelloWithDefaultFontColor();     
  5.             sayHelloWithRedFontColor();     
  6.   
  7.     }  
  8.     @NewAnnonation("say method")  
  9.     public static  void saying(){  
  10.           
  11.     }  
  12.     //此时的fontColor为默认的RED  
  13.     @Greeting(name="defaultfontcolor")  
  14.     public static void sayHelloWithDefaultFontColor() {     
  15.           
  16.     }  
  17.     //现在将fontColor改为BLUE  
  18.     @Greeting(name="notdefault",fontColor=Greeting.FontColor.BLUE)  
  19.     public static void sayHelloWithRedFontColor() {     
  20.              
  21. }  

 

 

(3)注释的高级应用

   限制注释的使用范围

   @Target指定ElementType属性

  

Java代码
  1.  package java.lang.annotation;     
  2. public enum ElementType {     
  3.   TYPE,     
  4.   // 用于类,接口,枚举但不能是注释  
  5.   FIELD,     
  6.   // 字段上,包括枚举值    
  7.   METHOD,     
  8.   // 方法,不包括构造方法  
  9.   PARAMETER,     
  10.   // 方法的参数  
  11.   CONSTRUCTOR,     
  12.   //构造方法  
  13.   LOCAL_VARIABLE,     
  14.   // 本地变量或catch语句   
  15.   ANNOTATION_TYPE,     
  16.   // 注释类型(无数据)    
  17.   PACKAGE     
  18.   // Java包    
  19. }    

  

注解保持性策略

 

Java代码
  1. //限制注解使用范围  
  2. @Target({ElementType.METHOD,ElementType.CONSTRUCTOR})  
  3. public @interface Greeting {  
  4.   
  5.     //使用枚举类型  
  6.     public enum FontColor{  
  7.        BLUE,RED,GREEN  
  8.     };  
  9.     String name();  
  10.     FontColor fontColor() default FontColor.RED;  
  11. }  

 

Java编译器编译时,它会识别在源代码里添加的注释是否还会保留,这就是RetentionPolicy。下面是Java定义的RetentionPolicy枚举:

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

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

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

按照规定使用注释,但是并不将它保留到编译后的类文件中

 

  

Java代码
  1. package java.lang.annotation;     
  2. public enum RetentionPolicy {     
  3.   SOURCE,     
  4.   // 此类型会被编译器丢弃    
  5.   CLASS,     
  6.   // 此类型注释会保留在class文件中,但JVM会忽略它    
  7.   RUNTIME     
  8.   // 此类型注释会保留在class文件中,JVM会读取它     
  9. }    

  

Java代码
  1. //让保持性策略为运行时态,即将注解编码到class文件中,让虚拟机读取  
  2. @Retention(RetentionPolicy.RUNTIME)  
  3. public @interface Greeting {  
  4.   
  5.     //使用枚举类型  
  6.     public enum FontColor{  
  7.        BLUE,RED,GREEN  
  8.     };  
  9.     String name();  
  10.     FontColor fontColor() default FontColor.RED;  
  11. }  

 

文档化功能

Java提供的Documented元注释跟Javadoc的作用是差不多的,其实它存在的好处是开发人员可以定制Javadoc不支持的文档属性,并在开发中应用。它的使用跟前两个也是一样的,简单代码示例如下:

 

Java代码
  1. //让它定制文档化功能  
  2. //使用此注解时必须设置RetentionPolicy为RUNTIME  
  3. @Documented  
  4. public @interface Greeting {  
  5.   
  6.     //使用枚举类型  
  7.     public enum FontColor{  
  8.        BLUE,RED,GREEN  
  9.     };  
  10.     String name();  
  11.     FontColor fontColor() default FontColor.RED;  
  12. }  

  

标注继承

 

Java代码
  1. //让它允许继承,可作用到子类  
  2. @Inherited  
  3. public @interface Greeting {  
  4.   
  5.     //使用枚举类型  
  6.     public enum FontColor{  
  7.        BLUE,RED,GREEN  
  8.     };  
  9.     String name();  
  10.     FontColor fontColor() default FontColor.RED;  
  11. }  

 

 

(4)读取注解信息

属于重点,在系统中用到注解权限时非常有用,可以精确控制权限的粒度

 

Java代码
  1. package com.iwtxokhtd.annotation;  
  2. import java.lang.annotation.Annotation;  
  3. import java.lang.reflect.Method;  
  4.   
  5. //读取注解信息  
  6. public class ReadAnnotationInfoTest {  
  7.     public static void main(String[] args)throws Exception {  
  8.         //测试AnnotationTest类,得到此类的类对象  
  9.         Class c=Class.forName("com.iwtxokhtd.annotation.AnnotationTest");  
  10.         //获取该类所有声明的方法  
  11.         Method []methods=c.getDeclaredMethods();  
  12.         //声明注解集合  
  13.         Annotation[] annotations;  
  14.         //遍历所有的方法得到各方法上面的注解信息  
  15.         for(Method method:methods){  
  16.             //获取每个方法上面所声明的所有注解信息  
  17.             annotations=method.getDeclaredAnnotations();  
  18.             //再遍历所有的注解,打印其基本信息  
  19.             for(Annotation an:annotations){  
  20.             System.out.println("方法名为:"+method.getName()+" 其上面的注解为:"+an.annotationType().getSimpleName());  
  21.                 Method []meths=an.annotationType().getDeclaredMethods();  
  22.                 //遍历每个注解的所有变量  
  23.                 for(Method meth:meths){  
  24.                     System.out.println("注解的变量名为:"+meth.getName());  
  25.                 }  
  26.                   
  27.             }  
  28.         }  
  29.   
  30.     }  
  31.   
  32. }  

 

 


转自:http://iwtxokhtd.javaeye.com/blog/359939
原创粉丝点击