《Java编程思想》学习笔记17——注解Annotation

注解Annotation又叫元数据,是JDK5中引入的一种以通用格式为程序提供配置信息的方式。使用注解Annotation可以使元数据写在程序源码中,使得代码看起来简洁,同时编译器也提供了对注解Annotation的类型检查,使得在编译期间就可以排除语法错误。

1JDK内置的3中Annotation:

在JDK5中,内置了3个通用目的的注解Annotation,这三个内置的注解在java.lang包下:

(1).@Override

这个注解常用在继承类或实现接口的子类方法上,表面该方法是子类覆盖父类的方法,该方法的方法签名要遵循覆盖方法的原则:即访问控制权限必能比父类更严格,不能比父类抛出更多的异常。

(2).@Deprecated

这个注解告诉编译器该元素是过时的,即在目前的JDK版本中已经有新的元素代替该元素。

(3).@SuppressWarnings

该注解关闭编译器中不合适的警告,即强行压制编译器的警告提示。

2.注解Annotation的定义:

注解Annotation的定义和接口类似,实际上,编译器也把注解Annotationn像接口一样编译成class字节码文件。例如:

[java]  view plain copy
  1. import java.lang.annotation.*;  
  2.   
  3. @Target(ElementType.METHOD)  
  4. @Retention(RetentionPolicy.RUNTIME)  
  5. public @interface Test{}  

像这种没有任何元素的空注解Annotation叫做标记Annotation.

在声明注解的时候往往需要使用@Target,@Retention等注解,这种注解被称为注解的注解(元数据注解),即是专门用于处理注解Annotation本身的。

(1).@Target注解:

用于指示注解所应用的目标程序元素种类,该注解常和ElementType枚举类型一起联合使用,ElementType枚举提供了java程序中声明的元素类型如下:

  1. ANNOTATION_TYPE:注释类型声明。
  2. CONSTRUCTOR:构造方法声明。
  3. FIELD:字段声明(包括枚举常量)。
  4. LOCAL_VARIABLE:局部变量声明。
  5. METHOD:方法声明。
  6. PACKAGE:包声明。
  7. PARAMETER:参数声明。
  8. TYPE::类,接口或枚举声明。

(2).@Retention注解:

该注解用于指示所定义的注解类型的注释在程序声明周期中得保留范围,该注解常和RetentionPolicy枚举联合使用。RetentionPolicy枚举常量定义了注解在代码中的保留策略:

  1. CLASS:编译器把注解记录在类文件中,但在运行时JVM不需要保留注解。
  2. RUNTIME:编译器把注解记录在类文件中,在运行时JVM将保留注解,因此可以通过反射机制读取注解。
  3. SOURCE:仅保留在源码中,编译器在编译时就要丢弃掉该注解。

3.创建和处理自定义注解Annotation:

正常使用注解时,需要在注解中定义元素,用于接收程序设置的值,正常定义注解的例子如下:

[java]  view plain copy
  1. import java.lang.annotation.*;  
  2.   
  3. @Target(ElementType.METHOD)  
  4. @Retention(RetentionPolicy.RUNTIME)  
  5. public @interface UseCase{  
  6.     public int id();  
  7.     public String description() default “no description”;  
  8. }  

正常定义注解Annotation的方式类似定义接口,id和description是注解UseCase的属性,而不是方法,注解中不能定义方法只能定义属性。其中description属性有默认的值“no description“,即在使用时如果没有指定description的值,则程序使用其默认值。

上面UseCase注解用于跟踪方法的测试用例说明,使用上面注解的例子如下:

[java]  view plain copy
  1. import java.util.*;  
  2.   
  3. public class PasswordUtils{  
  4.     @UseCase(id = 47, description = “Passwords must contain at least one numeric”)  
  5.     public Boolean validatePassword(String password){  
  6.         return (password.mathes(“\\w*\\d\\w*”));  
  7. }  
  8. @UseCase(id = 48)  
  9. public String encryptPassword(Srring password){  
  10.     return new StringBuilder(password).reverse().toString();  
  11. }  
  12. @UseCase(id = 49, description = “New passwords can’t equal previously used ones”)  
  13. public Boolean checkForNewPassword(List<String> prevPasswords, String password){  
  14.     return !prevPasswords.contains(password);  
  15. }  
  16. }  

JDK5中提供了Annotation相关的API,结合使用java的反射机制可以实现自定义的Annotation注解处理器(JDK中也提供了使用APT,Annotationprocess tool方式处理注解,在后面会讲解),处理上述Annotation的例子如下:

[java]  view plain copy
  1. import java.lang.reflect.*;  
  2. import java.util.*;  
  3.   
  4. public class UseCaseTracker{  
  5.     public static void traceUseCases(List<Integer> useCases, Class<?> clazz){  
  6.         //获取指定类中所有声明的方法  
  7. for(Method m : clazz.getDeclaredMethods()){  
  8.     //获取方法上指定类型的注解  
  9.             UseCase uc = m.getAnnotation(UseCase.class);  
  10.             if(uc != null){  
  11.     System.out.println(“Found Use Case:” + uc.id() + “ ” + uc.description());  
  12.     useCases.remove(new Integer(uc.id()));  
  13. }  
  14. }  
  15. for(int i : useCases){  
  16.     System.out.println(“Warning: Missing use case-” + i);  
  17. }  
  18. }  
  19. public static void main(String[] args){  
  20.     List<Integer> useCases = new ArrayLis<Integer>();  
  21.     Collections.addAll(useCases, 47484950);  
  22.     trackUseCases(useCases, PasswordUtils.class);  
  23. }  
  24. }  

输出结果:

Found Use Case:47 Passwords must contain at least onenumeric

Found Use Case:48 no description

Found Use Case:49 New Passwords can’t equal previously usedones

Warning: Missing use case-50

注意:使用反射获取到注解对象之后,类似使用调用方法的方式获取注解的值,如uc.id()等。另外,注解不支持继承,因此声明注解时不能使用extends和implements关键字。

4.Annotation注解元素:

Annotation注解中的元素只能是下面的数据类型:

(1).java的8中基本类型,如int, boolean等等,如果可以自动装箱和拆箱,则可以使用对应的对象包装类型。

(2).String类型。

(3).Class类型。

(4).Enums类型。

(5).Annotation类型。

(6).上面类型的数组。

除了上面这些类型以外,如果在注解中定义其他类型的数据,编译器将会报错。

注意:注解中的元素要么指定默认值,要么由使用的类赋值,如果即没有默认值,使用类也没有赋值的话,注解元素是不会像普通类成员变量一样给定默认值,即必须赋值或者显示指定默认值。默认值例子如下:

[java]  view plain copy
  1. import java.lang.annotation.*;  
  2.   
  3. @Target(ElementType.METHOD)  
  4. @Retention(RetentionPolicy.RUNTIME)  
  5. public @interface DefaultValue{  
  6.     public int id() default -1;  
  7.     public String description() default “”;  
  8. }  

5.一个使用Annotation实现ORM的例子:

从EJB3之后,EJB的实体Bean持久化技术被单独抽取出来形成了JPA技术,JPA和Hibernate3之后都支持使用Annotation注解方式进行对象和关系型数据库映射(ObjectRelationship Mapping, ORM),下面使用Annotation注解方式实现一个简单的ORM功能:

(1).相关注解:

[java]  view plain copy
  1. import java.lang.annotation.*;  
  2.   
  3. @Target(ElementType.TYPE)//该注解只能应用在类上  
  4. @Retention(RetentionPolicy.RUNTIME)  
  5. public @interface DBTable{//指定数据库名称  
  6.     public String name() default “”;  
  7. }  
  8.   
  9. @Target(ElementType.FIELD)  
  10. @Retention(RetentionPolicy.RUNTIME)  
  11. public @interface Constraints{//数据库约束  
  12.     boolean primaryKey() default false;  
  13.     boolean allowNull() default true;  
  14.     boolean unique() default false;  
  15. }  
  16.   
  17. @Target(ElementType.FIELD)  
  18. @Retention(RetentionPolicy.RUNTIME)  
  19. public @interface SQLString{//String类型数据  
  20.     int value() default 0;  
  21.     String name() default “”;  
  22.     Constraints constraints() default @Constraints;//注解的属性元素也是注解  
  23. }  
  24.   
  25. @Target(ElementType.FIELD)  
  26. @Retention(RetentionPolicy.RUNTIME)  
  27. public @interface SQLInteger{//int类型数据  
  28.     String name() default “”;  
  29.     Constraints constraints() default @Constraints;   
  30. }  

(2).使用Annotation注解的实体类:

[java]  view plain copy
  1. @DBTable(name=”MEMBER”)  
  2. public class Member{  
  3.     @SQLString(30)//当只指定一个属性的值,并且该属性名为value时,不用写属性名称  
  4.     String firstName;  
  5.     @SQLString(50)  
  6.     String lastName;  
  7.     @SQLInteger  
  8.     Integer age;  
  9.     @String(value=30, constraints=@Constraints(primaryKey = true))  
  10.     String handle;  
  11.     static int memberCount;  
  12. }  

注意:当为注解多于1个以上的属性指定值时,即使有value属性也要写value的属性名称。

(3).实现自定义注解处理器:

[java]  view plain copy
  1. import java.lang.annotation.*;  
  2. import java.lang.reflect.*;  
  3. import java.util.*;  
  4.   
  5. public class TableCreator{  
  6.     public static void mian(String[] args)throws Exception{  
  7.         Member m = new Member();  
  8.         Class clazz = m.getClass();  
  9.         String tableName = null;  
  10.         DBTable dbTable =  class.getAnnotation(DBTable.class);  
  11.         if(db != null){  
  12.             tableName = db.name();  
  13. }  
  14. If(tableName == null){//如果没有指定Table名称,使用类名  
  15.     tableName = clazz.getName().toUpperCase;  
  16. }  
  17. List<String> columnDefs = new ArrayList<String>();  
  18. //构造SQL创建列语句  
  19. for(Field f : clazz.getDeclaredFields()){//遍历类中声明的所有字段  
  20.     String columnName = null;  
  21.     //获取当前字段上声明的所有注解  
  22.     Annotationn[] anns = f.getDeclaredAnnotationns();  
  23.     if(anns.length() < 1){//当前字段上没有声明注解  
  24.         continue;  
  25. }  
  26. if(anns[0instanceof SQLInteger){//注解数组第一个定义的是数据类型  
  27.     SQLInteget sInt = (SQLInteger) anns[0];  
  28.     if(sInt.name().length() < 1){//如果没有指定列名称,则使用字段名称  
  29.         columnName = f.getName().toUpperCase();  
  30. }else{  
  31.     columnName = sInt.name();  
  32. }  
  33. columnDefs.add(columnName + “ INT” + getConstraints(sInt.constraints()));  
  34. }  
  35. if(anns[0instanceof SQLString){  
  36.     SQLString sString = (SQLString) anns[0];  
  37.     if(sString.name().length() < 1){//如果没有指定列名称,则使用字段名称  
  38.         columnName = f.getName().toUpperCase();  
  39. }else{  
  40.     columnName = sInt.name();  
  41. }  
  42. columnDefs.add(columnName + “ VARCHAR(” + sString.value() +”)”  
  43.  + getConstraints(sString.constraints()));  
  44. }  
  45. }  
  46. StringBuilder createCommand = new StringBuilder(“CREATE TABLE”   
  47. + tableName + “(”);  
  48.             for(String columnDef : columnDefs){  
  49.                 createCommand.append(“\n ” + columnDef + “,”);  
  50. }  
  51. //删除最后的”,”  
  52. String tableCreate = createCommand.subString(0, createCommand.length() - 1)   
  53. + “);”;  
  54.             System.out.println(“Table creation SQL for ” + className + “ is :\n”   
  55. + tableCreate);  
  56. }  
  57. //获取约束  
  58. Private static String getConstraints(Constraints con){  
  59.     String constraints = “”;  
  60.     if(!con.allowNnull()){  
  61.         constraints += “ NOT NULL”;  
  62. }  
  63. if(con.primaryKey()){  
  64.         constraints += “ PRIMARY KEY”;  
  65. }  
  66. if(con.unique()){  
  67.         constraints += “ UNIQUE”;  
  68. }  
  69. return constraints;  
  70. }  
  71. }  

输出结果:

Table creation SQL for Member is:

CREATE TABLE MEMBER(

            FIRSTNAME  VARCHAR(30),

            LASTNAME   VARCHAR(50),

            AGE  INT,

            HANDLE    VARCHAR(30)  PRIMARY KEY);

6.使用apt处理Annotation注解:

Annotation processing tool, apt是sun提供的第一个版本的Annotation注解处理器,apt的使用和javac类似,是真的未编译的源码,而非已经编译的class字节码文件,使用apt的时候不能使用java的反射机制,因为源码尚未编译,需要使用mirrorAPI,mirror API可以使得apt看到未编译源代码中的方法,字段和类信息。使用apt的例子如下:

(1).注解:

[java]  view plain copy
  1. package annotations;  
  2.   
  3. import java.lang.annotation.*;  
  4.   
  5. @Target(ElementType.TYPE)  
  6. @Retention(RetentionPolicy.SOURCE)  
  7. public @interface ExtractInterface{  
  8.     public String value();  
  9. }  

这个注解用于从使用该注解的类中抽象公共的方法,并为该类生成一个接口。

(2).使用注解的类:

[java]  view plain copy
  1. package annotations;  
  2.   
  3. @ExtractInterface(“IMultiplier”)  
  4. public class Multiplier{  
  5.     public int multiply(int x, int y){  
  6.         int total = 0;  
  7.         for(int i = 0; I < x; i++){  
  8.     total = add(total, y);  
  9. }  
  10. return total;  
  11. }  
  12. private int add(int x, int y){  
  13.     return x + y;  
  14. }  
  15. }  

(3).注解处理器:

[java]  view plain copy
  1. package annotations;  
  2.   
  3. import com.sun.mirror.apt.*;  
  4. import com.sun.mirror.declaration.*;  
  5. import java.io.*;  
  6. import java.util.*;  
  7.   
  8. public class InterfaceExtractorProcessor implements AnnotationProcessor{  
  9.     //注解处理器的工作环境  
  10. private final AnnotationProcessorEnvironment env;  
  11.     private List<MethodDeclaration> interfaceMethods =   
  12. new ArrayList< MethodDeclaration>();  
  13.     public InterfaceExtractorProcessor(AnnotationProcessEnvironment env){  
  14.     this.env = env;  
  15. }  
  16. public void process(){  
  17.     //查询注解处理器环境中的类型声明  
  18.     for(TypeDeclaration typeDecl : env.getSpecifiedTypeDeclarations()){  
  19.         //获取注解  
  20. ExtractInterface annot = typeDecl.getAnnotation(ExtractInterface.class);  
  21.         if(annot == null){  
  22.             break;  
  23. }  
  24. //遍历所有添加注解的方法  
  25. for(MethodDeclaration m : typeDecl.getMethods()){  
  26.     //方法签名中的访问控制符是public的,且不是静态方法  
  27. if(m.getModifiers().contains(Modifier.PUBLIC) &&   
  28. !(m.getModifiers().contains(Modifier.STATIC))){  
  29.     interfaceMethods.add(m);  
  30. }  
  31. }  
  32. if(interfaceMethods.size() > 0){  
  33.     try{  
  34.         PrintWriter writer = env.getFiler().createSourceFile(annot.value());  
  35.         writer.println(“package ” + typeDecl.getPackage().getQualifiedName()   
  36. +  “;”);  
  37.                     writer.println(“public interface ” + annot.value() + “{“);  
  38.                     //写方法声明  
  39.                     for(MethodDeclaration m : interfaceMethods){  
  40.     writer.print(“ public’);  
  41.     writer.print(m.getReturnType() + “ ”);  
  42.     writer.print(m.getSimpleName() + “ ”);  
  43.     int i = 0;  
  44.     //写方法参数列表  
  45.     for(ParametherDeclaration parm : m.getParameters()){  
  46.     writer.print(parm.getType() + “ ” + parm.getSimpleName());  
  47.     if( ++i < m.getParameters().size()){  
  48.     writer.print(“, ”);  
  49. }  
  50. }  
  51. writer.println(“);”)  
  52. }  
  53. writer.println(“}”);  
  54. writer.close();  
  55. }catch(Exception e){  
  56.     Throw new RuntimeException(e);  
  57. }  
  58. }  
  59. }  
  60. }  
  61. }  

使用sun的mirror API可以获取源码中的Field, type, method等信息。

(4).为apt工厂提供注解处理器:

[java]  view plain copy
  1. package annotations;  
  2.   
  3. import com.sun.mirror.apt.*;  
  4. import com.sun.mirror.declaration.*;  
  5. import java.util.*;  
  6.   
  7. public class InterfaceExtractorProcessorFactory implements AnnotationProcessorFactory{  
  8.     //获取注解处理器  
  9. public AnnotationProcessor getProcessorFor(Set<AnnotationTypeDeclaration> atds,  
  10. AnnotationProcessorEnvironment env){  
  11.     return new InterfaceExtractorProcess(env);  
  12. }  
  13. //定义注解处理器所支持的注解类型  
  14. public Collection<String> supportedAnnotationTypes(){  
  15.     return Collections.singleton(“ExtractInterface”);  
  16. }  
  17. //定义注解处理器支持的选项  
  18. public Collection<String> supportedOptions(){  
  19.     return Collections.emptySet();  
  20. }  
  21. }     

(5).运行apt:

使用下面的命令允许apt:

apt-factory annotations.InterfaceExtractorProcessorFactory Multiplier.java –s ../annotations

输出结果:

package annotations;

public interface IMultiplier{

            public int multiply(intx, int y);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值