当前位置: 移动技术网 > IT编程>开发语言>Java > 详解Java编程中Annotation注解对象的使用方法

详解Java编程中Annotation注解对象的使用方法

2019年07月22日  | 移动技术网IT编程  | 我要评论

赖皮点豆,金民钟结婚了吗,肉松茸

注解(也被称为元数据)为我们在代码中添加信息提供了一种形式化的方法,使我们可以在稍后某个时刻非常方便地使用这些数据。
 
1.基本语法
java se5内置三种标准注解
@override:表示当前的方法定义将覆盖超类中的方法.如果你不小心拼写错误,或者方法签名对不上被覆
盖的方法,编译器就会发出错误提示
@deprecated:如果程序员使用了注解为它的元素,那么编译器就会发出警告信息
@supperesswarnings:关闭不当的编译器警告信息.
java se5内置四种元注解
@target:表示该注解可以用于什么地方.可能的elementtype参数包括:
1)constructor:构造器的声明
2)field:域声明(包括enum实例)
3)local_variable:局部变量声明
4)method:方法声明
5)package:包声明
6)parameter:参数声明
7)type:类、接口(包括注解类型)或enum声明
@retention:表示需要在什么级别保存该注解信息.可选的retentionpolicy参数包括:
1)source:注解将被编译器丢弃
2)class:注解在class文件中可用,但会被vm丢弃
3)runtime:vm将在运行期也保留注解,因此可以通过反射机制读取注解的信息
@documented:将此注解包含在javadoc中
@inherited:允许子类继承父类中的注解
大多数时候,程序员主要是定义自己的注解,并编写自己的处理器来处理它们.
usecase.java   

package com;  
 
import java.lang.annotation.elementtype;  
import java.lang.annotation.retention;  
import java.lang.annotation.retentionpolicy;  
import java.lang.annotation.target;  
 
@target(elementtype.method)//用来定义你的注解将应用在什么地方,本处应用为方法  
//用来定义该注解在哪一个级别可用,在源代码中(source)类文件中(class)或者运行时(runtime)  
@retention(retentionpolicy.runtime)  
public @interface usecase {  
 public int id();  
 public string description()default "no description";  
}  
 
 passwordutils .java  
package com;  
 
public class passwordutils {  
 @usecase(id=47,description="passwords must contain at least one numeric")  
 public boolean validatepassword(){  
 return true;  
 }  
  
 @usecase(id=48)  
 public string encryptpassword(string password){  
 return password;  
 }  
  
 @usecase(id=49,description="jong_cai")  
 public void showname(){  
 system.out.println("jong_cai");  
 }  
}  

 
2.编写注解处理器
 如果没有用来读取注解的工具,那注解也不会比注释更有用.使用注解的过程中.很重要的一个部
分就是创建与使用注解处理器.java se5扩展了反射机制的api,以帮助程序员构造这类工具.同时,它还提供了一个外部工具apt帮助程序员解析带有注解的java源代码.下面是一个非常简单的注解处理器,我们将用它来读取passwordutils类,并使用反射机制查找@usecase标记.我们为其提供了一组id值得,然后它会列出在passwordutils中找到的用例,以及缺失的用例.

 usecasetracker.java 
package com;  
 
import java.lang.reflect.method;  
import java.util.arraylist;  
import java.util.collections;  
import java.util.list;  
 
public class usecasetracker {  
 public static void trackusecases(list<integer> list, class<?> cl) {  
 for (method m : cl.getdeclaredmethods()) {  
  usecase us = m.getannotation(usecase.class);  
  if (us != null) {  
  system.out.println("found use case:" + us.id() + " " 
   + us.description());  
  list.remove(new integer(us.id()));  
  }  
 }  
 for (int i : list) {  
  system.out.println("warning:missing use case-" + i);  
 }  
 }  
 
 public static void main(string[] args) {  
 list<integer> list = new arraylist<integer>();  
 collections.addall(list, 47,48,49,50,51);  
 trackusecases(list, passwordutils.class);  
 }  
}  

 
这个程序用到了两个反射的方法:getdeclaredmethods()和getannotation(),它们都属于annotatedelement接口(class,method与field等类都实现了该接口).getannotation()方法返回指定类型的注解对象,在这里就是usecase,如果被注解的方法上没有该类型的注解,则返回null值.然后我们通过调用id()和description()方法从返回的usecase对象中提取元素的值.其中encryptpassword()方法在注解的时候没有指定description的值,因此处理器在处理它对应的注解时,通过description()方法取得的是默认值no description.

annotation在java的世界正铺天盖地展开,有空写这一篇简单的annotations的文章,算是关于annotation入门的文章吧,希望能各位们能抛砖,共同学习......
不讲废话了,实践才是硬道理.

3.实例
下面讲一下annotation的概念先,再来讲一下怎样设计自己的annotation.
首先在jdk自带的java.lang.annotation包里,打开如下几个源文件:
  
源文件target.java

@documented 
@retention(retentionpolicy.runtime)  
@target(elementtype.annotation_type)  
public @interface target {  
  elementtype[] value();  

@documented 
@retention(retentionpolicy.runtime) 
@target(elementtype.annotation_type) 
public @interface target { 
  elementtype[] value(); 
} 

  
其中的@interface是一个关键字,在设计annotations的时候必须把一个类型定义为@interface,而不能用class或interface关键字(会不会觉得sun有点吝啬,偏偏搞得与interface这么像).
  
源文件retention.java

@documented 
@retention(retentionpolicy.runtime)  
@target(elementtype.annotation_type)  
public @interface retention {  
  retentionpolicy value();  
} 

@documented 
@retention(retentionpolicy.runtime) 
@target(elementtype.annotation_type) 
public @interface retention { 
  retentionpolicy value(); 
} 


看到这里,大家可能都模糊了,都不知道在说什么,别急,往下看一下. 在上面的文件都用到了retentionpolicy,elementtype这两个字段,你可能就会猜到这是两个java文件.的确,这两个文件的源代码如下:
  
源文件retentionpolicy.java

public enum retentionpolicy {  
 source,  
 class,  
 runtime  
} 

public enum retentionpolicy { 
 source, 
 class, 
 runtime 
} 

这是一个enum类型,共有三个值,分别是source,class 和 runtime.
source代表的是这个annotation类型的信息只会保留在程序源码里,源码如果经过了编译之后,annotation的数据就会消失,并不会保留在编译好的.class文件里面。
class的意思是这个annotation类型的信息保留在程序源码里,同时也会保留在编译好的.class文件里面,在执行的时候,并不会把这一些信息加载到虚拟机(jvm)中去.注意一下,当你没有设定一个annotation类型的retention值时,系统默认值是class.
第三个,是runtime,表示在源码、编译好的.class文件中保留信息,在执行的时候会把这一些信息加载到jvm中去的.
举一个例子,如@override里面的retention设为source,编译成功了就不要这一些检查的信息;相反,@deprecated里面的retention设为runtime,表示除了在编译时会警告我们使用了哪个被deprecated的方法,在执行的时候也可以查出该方法是否被deprecated.


源文件elementtype.java

public enum elementtype {  
 type, field, method, parameter, constructor,  
 local_variable, annotation_type,package  
} 

public enum elementtype { 
 type, field, method, parameter, constructor, 
 local_variable, annotation_type,package 
} 

   @target里面的elementtype是用来指定annotation类型可以用在哪一些元素上的.说明一下:type(类型), field(属性), method(方法), parameter(参数), constructor(构造函数),local_variable(局部变量), annotation_type,package(包),其中的type(类型)是指可以用在class,interface,enum和annotation类型上.
   另外,从1的源代码可以看出,@target自己也用了自己来声明自己,只能用在annotation_type之上.
   如果一个annotation类型没有指明@target使用在哪些元素上,那么它可以使用在任何元素之上,这里的元素指的是上面的八种类型.
   举几个正确的例子:
   @target(elementtype.method)
   @target(value=elementtype.method)
   @target(elementtype.method,elementtype.constructor)  
   具体参考一下javadoc文档
  
   源文件它们都使用了@documented,@documented的目的就是让这一个annotation类型的信息能够显示在javaapi说明文档上;没有添加的话,使用javadoc生成api文档的时候就会找不到这一个类型生成的信息.
   另外一点,如果需要把annotation的数据继承给子类,那么就会用到@inherited这一个annotation类型. 
   
下面讲的设计一个最简单的annotation例子,这一例子共用四个文件; 
description.java

package lighter.javaeye.com;  
 
import java.lang.annotation.documented;  
import java.lang.annotation.elementtype;  
import java.lang.annotation.retention;  
import java.lang.annotation.retentionpolicy;  
import java.lang.annotation.target;  
 
@target(elementtype.type)  
@retention(retentionpolicy.runtime)  
@documented 
public @interface description {  
  string value();  
} 

package lighter.javaeye.com; 
 
import java.lang.annotation.documented; 
import java.lang.annotation.elementtype; 
import java.lang.annotation.retention; 
import java.lang.annotation.retentionpolicy; 
import java.lang.annotation.target; 
 
@target(elementtype.type) 
@retention(retentionpolicy.runtime) 
@documented 
public @interface description { 
  string value(); 
} 

  
说明:所有的annotation会自动继承java.lang.annotation这一个接口,所以不能再去继承别的类或是接口.
最重要的一点,annotation类型里面的参数该怎么设定:
第一,只能用public或默认(default)这两个访问权修饰.例如,string value();这里把方法设为defaul默认类型.
第二,参数成员只能用基本类型byte,short,char,int,long,float,double,boolean八种基本数据类型和string,enum,class,annotations等数据类型,以及这一些类型的数组.例如,string value();这里的参数成员就为string.
第三,如果只有一个参数成员,最好把参数名称设为"value",后加小括号.例:上面的例子就只有一个参数成员.

name.java

package lighter.javaeye.com;  
 
import java.lang.annotation.documented;  
import java.lang.annotation.elementtype;  
import java.lang.annotation.retention;  
import java.lang.annotation.retentionpolicy;  
import java.lang.annotation.target;  
 
//注意这里的@target与@description里的不同,参数成员也不同  
@target(elementtype.method)  
@retention(retentionpolicy.runtime)  
@documented 
public @interface name {  
  string originate();  
  string community();  
} 

package lighter.javaeye.com; 
 
import java.lang.annotation.documented; 
import java.lang.annotation.elementtype; 
import java.lang.annotation.retention; 
import java.lang.annotation.retentionpolicy; 
import java.lang.annotation.target; 
 
//注意这里的@target与@description里的不同,参数成员也不同 
@target(elementtype.method) 
@retention(retentionpolicy.runtime) 
@documented 
public @interface name { 
  string originate(); 
  string community(); 
} 


javaeyer.java

package lighter.javaeye.com;  
 
@description("javaeye,做最棒的软件开发交流社区")  
public class javaeyer {  
  @name(originate="创始人:robbin",community="javaeye")  
  public string getname()  
  {  
    return null;  
  }  
    
  @name(originate="创始人:江南白衣",community="springside")  
  public string getname2()  
  {  
    return "借用两位的id一用,写这一个例子,请见谅!";  
  }  
} 


package lighter.javaeye.com; 
 
@description("javaeye,做最棒的软件开发交流社区") 
public class javaeyer { 
  @name(originate="创始人:robbin",community="javaeye") 
  public string getname() 
  { 
    return null; 
  } 
   
  @name(originate="创始人:江南白衣",community="springside") 
  public string getname2() 
  { 
    return "借用两位的id一用,写这一个例子,请见谅!"; 
  } 
} 

写一个可以运行提取javaeyer信息的类testannotation

 

package lighter.javaeye.com;  
 
 import java.lang.reflect.method;  
 import java.util.hashset;  
 import java.util.set;  
 
 public class testannotation {  
  /** 
   * author lighter 
   * 说明:具体关天annotation的api的用法请参见javadoc文档 
   */ 
    public static void main(string[] args) throws exception {  
    string class_name = "lighter.javaeye.com.javaeyer";  
    class test = class.forname(class_name);  
    method[] method = test.getmethods();  
    boolean flag = test.isannotationpresent(description.class);  
    if(flag)  
    {  
      description des = (description)test.getannotation(description.class);  
      system.out.println("描述:"+des.value());  
      system.out.println("-----------------");  
    }  
      
    //把javaeyer这一类有利用到@name的全部方法保存到set中去  
    set<method> set = new hashset<method>();  
    for(int i=0;i<method.length;i++)  
    {  
      boolean otherflag = method[i].isannotationpresent(name.class);  
      if(otherflag) set.add(method[i]);  
    }  
    for(method m: set)  
    {  
      name name = m.getannotation(name.class);  
      system.out.println(name.originate());  
      system.out.println("创建的社区:"+name.community());  
    }  
   }  
} 

 package lighter.javaeye.com; 
 
 import java.lang.reflect.method; 
 import java.util.hashset; 
 import java.util.set; 
 
 public class testannotation { 
  /** 
   * author lighter 
   * 说明:具体关天annotation的api的用法请参见javadoc文档 
   */ 
    public static void main(string[] args) throws exception { 
    string class_name = "lighter.javaeye.com.javaeyer"; 
    class test = class.forname(class_name); 
    method[] method = test.getmethods(); 
    boolean flag = test.isannotationpresent(description.class); 
    if(flag) 
    { 
      description des = (description)test.getannotation(description.class); 
      system.out.println("描述:"+des.value()); 
      system.out.println("-----------------"); 
    } 
     
    //把javaeyer这一类有利用到@name的全部方法保存到set中去 
    set<method> set = new hashset<method>(); 
    for(int i=0;i<method.length;i++) 
    { 
      boolean otherflag = method[i].isannotationpresent(name.class); 
      if(otherflag) set.add(method[i]); 
    } 
    for(method m: set) 
    { 
      name name = m.getannotation(name.class); 
      system.out.println(name.originate()); 
      system.out.println("创建的社区:"+name.community()); 
    } 
   } 
} 

运行结果:

描述:javaeye,做最棒的软件开发交流社区 
创始人:robbin 
创建的社区:javaeye 
创始人:江南白衣 
创建的社区:springside


如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网