Java Annotation(注解)

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

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

  1. 编写文档:通过代码里标识的元数据生成文档
  2. 代码分析:通过代码里标识的元数据对代码进行分析
  3. 通过代码里标识的元数据让编译器能实现基本的编译检查


        ● 基本内置注释
        @Override
        不用多说,用来标注方法是覆写父类的方法。

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

        @SuppressWarnings
        @SuppressWarnings 允许你选择性地取消特定代码段(即,类或方法)中的警告。其中的想法是当你看到警告时,你将调查它,如果你确定它不是问题,你就可以添加一个 @SuppressWarnings 注解,以使你不会再看到警告。虽然它听起来似乎会屏蔽潜在的错误,但实际上它将提高代码安全性,因为它将防止你对警告无动于衷 — 你看到的每一个警告都将值得注意。
        @SuppressWarnings 有如下参数:
        deprecation: 使用了过时的类或方法时的警告
        unchecked: 执行了未检查的转换时的警告
        fallthrough: 当 switch 程序块直接通往下一种情况而没有 Break 时的警告
        path: 在类路径、源文件路径等中有不存在的路径时的警告
        serial: 当在可序列化的类上缺少 serialVersionUID 定义时的警告
        finally: 任何 finally 子句不能正常完成时的警告
        all: 关于以上所有情况的警告

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

Java代码 复制代码
  1. public @interface MyAnnotation {   
  2.   
  3. }  
public @interface MyAnnotation {

}


        使用自定义的注释类型:

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


        为自定义注释添加变量:

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

 

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


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

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


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

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

}

@MyAnnonation("say method")
public static void saying() {
    	
}

// 此时的 fontColor 为默认的 RED
@Greeting(name="defaultfontcolor")
public static void sayHelloWithDefaultFontColor() {   
        
}

//现在将 fontColor 改为 BLUE
@Greeting(name="notdefault",fontColor=Greeting.FontColor.BLUE)
public static void sayHelloWithRedFontColor() {   
           
}



        ● 注释的高级应用
        限制注释的使用范围
        用 @Target 指定 ElementType 属性:

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

public enum ElementType {   
    // 用于类,接口,枚举但不能是注释
    TYPE,
    // 字段上,包括枚举值  
    FIELD,
    // 方法,不包括构造方法
    METHOD,
    // 方法的参数
    PARAMETER,
    // 构造方法
    CONSTRUCTOR,  
    // 本地变量或 catch 语句
    LOCAL_VARIABLE,
    // 注释类型(无数据)
    ANNOTATION_TYPE,
    // Java 包
    PACKAGE
}


        注解保持性策略

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


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

  1. 将注释保留在编译后的类文件中,并在第一次加载类时读取它
  2. 将注释保留在编译后的类文件中,但是在运行时忽略它
  3. 按照规定使用注释,但是并不将它保留到编译后的类文件中

 

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

public enum RetentionPolicy {   
    // 此类型会被编译器丢弃
    SOURCE,
    // 此类型注释会保留在class文件中,但JVM会忽略它
    CLASS,   
    // 此类型注释会保留在class文件中,JVM会读取它
    RUNTIME 
}

 

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


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

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



        标注继承

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



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

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() + " 其上面的注解为:" +    
  21.             an.annotationType().getSimpleName());   
  22.         Method []meths=an.annotationType().getDeclaredMethods();   
  23.         // 遍历每个注解的所有变量   
  24.         for (Method meth:meths) {   
  25.           System.out.println("注解的变量名为:"+meth.getName());   
  26.         }   
  27.       }   
  28.     }   
  29.   }   
  30. }  
package com.iwtxokhtd.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

//读取注解信息
public class ReadAnnotationInfoTest {
  public static void main(String[] args)throws Exception {
    // 测试 AnnotationTest 类,得到此类的类对象
    Class c=Class.forName("com.iwtxokhtd.annotation.AnnotationTest");
    // 获取该类所有声明的方法
    Method []methods=c.getDeclaredMethods();
    // 声明注解集合
    Annotation[] annotations;
    // 遍历所有的方法得到各方法上面的注解信息
    for (Method method:methods) {
      // 获取每个方法上面所声明的所有注解信息
      annotations=method.getDeclaredAnnotations();
      // 再遍历所有的注解,打印其基本信息
      for (Annotation an:annotations) {
        System.out.println("方法名为:"+ method.getName() + " 其上面的注解为:" + 
            an.annotationType().getSimpleName());
        Method []meths=an.annotationType().getDeclaredMethods();
        // 遍历每个注解的所有变量
        for (Method meth:meths) {
          System.out.println("注解的变量名为:"+meth.getName());
        }
      }
    }
  }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值