第二十章:注解

注解(元数据)为我们在代码中添加信息提供了一种形式化的方法,使我们能在以后方便使用这些数据。
java.lang中的注解:
· @Override
· @Deprecated
· @SuppressWarning
特点:

  1. 语言级概念,一旦构造出来,就享有编译器的类型检查保护
  2. 在实际的源代码级别保存所有的信息,而不是某种注释性的文字。使程序员拥有对源代码以及字节码强大的检查与操作能力

基本语法

与接口一样,注解也会编译成class文件。

//定义注解
@Target(ElementType.METHOD) //应用地方
@Retention(Retention.Policy.RUNTIME) //应用级别
public @interface UseCase {
  public int id();
  public String description() default "no descritpion";
}

//eg
@UseCase(id = 47, description =
  "Passwords must contain at least one numeric")
  public boolean validatePassword(String password) {
    return (password.matches("\\w*\\d\\w*"));
  }

元注解:

元注解 -
@Target ElementType参数:

CONSTRUCTOR:构造器的声明

FIELD:域声明(包括enum实例)

LOCAL_VARIABLE:局部变量声明

METHOD:方法声明

PACAKAGE:包声明

PARAMETER:参数声明

TYPE:类、接口(包括注解类型)或enum声明
@Retention 注解的生命时间

RetentionPolicy参数包括:

SOURCE:源码注解,      RetentionPolicy.SOURCE :

CLASS:编译时注解,默认值,注解在class文件中可用,但被类加载器加载字节码到内存时被VM丢弃,注解处理器

RUNTIME:运行时注解VM将在运行期也保留注解,因此可以通过反射读取注解信息。
@Ducumented 此注解包含在Javadoc中
@Inherited 允许子类继承父类的注解

注解元素:
注解包含的元素,可用类型:

  1. 所有基本类型
  2. String
  3. Class
  4. enum
  5. Annotation
  6. 以上类型的数组

默认值限制:
注解元素不能有不确定的值,要么有默认值,要么在使用注解是提供元素的值。而对于非基本类型的元素,不能使用null作为默认值。为了绕开这个约束,可以自己定义特殊的值表示某个元素不存在,比如空字符串或负数。
注解不支持继承
不能使用关键字extends来继承某个@interface。

继承的注解

- 编写自定义注解时未写@Inherited的运行结果: 编写自定义注解时写了@Inherited的运行结果:
子类的类上能否继承到父类的类上的注解?
子类方法,实现了父类上的抽象方法,这个方法能否继承到注解?
子类方法,继承了父类上的方法,这个方法能否继承到注解?
子类方法,覆盖了父类上的方法,这个方法能否继承到注解?

PS: @Inherited只能注解class的注解
子类可以继承到父类上的注解吗--有结论了

编写注解处理器

public class UseCaseTracker {
  public static void
  trackUseCases(List<Integer> useCases, Class<?> cl) {
    for(Method m : cl.getDeclaredMethods()) {//获取该类声明的方法
      UseCase uc = m.getAnnotation(UseCase.class);//返回指定类型的注解对象
      if(uc != null) {
        System.out.println("Found Use Case:" + uc.id() +
          " " + uc.description());
        useCases.remove(new Integer(uc.id()));
      }
    }
    for(int i : useCases) {
      System.out.println("Warning: Missing use case-" + i);
    }
  }
  public static void main(String[] args) {
    List<Integer> useCases = new ArrayList<Integer>();
    Collections.addAll(useCases, 47, 48, 49, 50);
    trackUseCases(useCases, PasswordUtils.class);
  }
}

getDeclaredMethods()和getAnnotation()都属于AnotatedElement接口,Class、Method和Field都实现了该接口。

@SQLString(30) //如果注解中定义了value的元素,可以使用泽中快捷方式赋值

一个数据库使用注解生成表的例子:
数据库注解:

//表注解
@Target(ElementType.TYPE) // Applies to classes only
@Retention(RetentionPolicy.RUNTIME)
public @interface DBTable {
  public String name() default "";
} 
//列限制注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Constraints {
  boolean primaryKey() default false;
  boolean allowNull() default true;
  boolean unique() default false;
}
//SQL整数
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLInteger {
  String name() default "";
  Constraints constraints() default @Constraints;
} ///:~
//SQL字符串
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SQLString {
  int value() default 0;
  String name() default "";
  Constraints constraints() default @Constraints;
} 

数据库bean例子

@DBTable(name = "MEMBER")
public class Member {
  @SQLString(30) String firstName;
  @SQLString(50) String lastName;
  @SQLInteger Integer age;
  @SQLString(value = 30,
  constraints = @Constraints(primaryKey = true))
  String handle;
  static int memberCount;
  public String getHandle() { return handle; }
  public String getFirstName() { return firstName; }
  public String getLastName() { return lastName; }
  public String toString() { return handle; }
  public Integer getAge() { return age; }
} ///:~

数据库注解处理器:

public static void main(String[] args) throws Exception {
    if(args.length < 1) {
      System.out.println("arguments: annotated classes");
      System.exit(0);
    }
    for(String className : args) {
      Class<?> cl = Class.forName(className);
      DBTable dbTable = cl.getAnnotation(DBTable.class);
      if(dbTable == null) {
        System.out.println(
          "No DBTable annotations in class " + className);
        continue;
      }
      String tableName = dbTable.name();
      // If the name is empty, use the Class name:
      if(tableName.length() < 1)
        tableName = cl.getName().toUpperCase();
      List<String> columnDefs = new ArrayList<String>();
      for(Field field : cl.getDeclaredFields()) {
        String columnName = null;
        Annotation[] anns = field.getDeclaredAnnotations();//返回注解数组
        if(anns.length < 1)
          continue; // Not a db table column
        if(anns[0] instanceof SQLInteger) {
          SQLInteger sInt = (SQLInteger) anns[0];
          // Use field name if name not specified
          if(sInt.name().length() < 1)
            columnName = field.getName().toUpperCase();
          else
            columnName = sInt.name();
          columnDefs.add(columnName + " INT" +
            getConstraints(sInt.constraints()));
        }
        if(anns[0] instanceof SQLString) {
          SQLString sString = (SQLString) anns[0];
          // Use field name if name not specified.
          if(sString.name().length() < 1)
            columnName = field.getName().toUpperCase();
          else
            columnName = sString.name();
          columnDefs.add(columnName + " VARCHAR(" +
            sString.value() + ")" +
            getConstraints(sString.constraints()));
        }
        StringBuilder createCommand = new StringBuilder(
          "CREATE TABLE " + tableName + "(");
        for(String columnDef : columnDefs)
          createCommand.append("\n    " + columnDef + ",");
        // Remove trailing comma
        String tableCreate = createCommand.substring(
          0, createCommand.length() - 1) + ");";
        System.out.println("Table Creation SQL for " +
          className + " is :\n" + tableCreate);
      }
    }
  }
  private static String getConstraints(Constraints con) {
    String constraints = "";
    if(!con.allowNull())
      constraints += " NOT NULL";
    if(con.primaryKey())
      constraints += " PRIMARY KEY";
    if(con.unique())
      constraints += " UNIQUE";
    return constraints;
  }
} 

上述处理例子是很幼稚的(因为修改表名只能重新编译java代码),可以了解一下成熟的将对象映射到关系数据库的方法。

使用apt处理注解

注解处理工具apt是有Sun公司提供的,被设计为操作java源文件。默认的话,apt会在处理完源文件后编译它们。如果在系统构建中自动创建了一些新的源文件,apt也会在新一轮检查处理,并将所有文件一同编译,再循环,直到没有新源文件产生。使用apt时无法使用反射,因为操作的是源代码而不是编译产生的类。
继承AnnotationProcessor重写process方法处理AnnotationProcessorFactory导出类传进去的AnnotationProcessorEnvironment对象,该对象可以获得注解及类信息。
补充:

  1. javassit处理字节码,可以用来修改class文件
  2. 注解处理器
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,744评论 25 709
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,007评论 6 342
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,281评论 19 139
  • 感赏自己早起做了一碗嫩滑可口的鸡蛋羹和其他饭菜,我还要继续努力提高自己的厨艺水平! 为了感谢曾经帮助过...
    水静我心阅读 239评论 2 1
  • 这是一个无聊的简书,只是为了尝试发一个简书
    尼克劳斯李阅读 207评论 0 0