Annotation的应用场合


annotation一般作为一种辅助途径,应用在软件框架或工具中,在这些工具类中根据不同的 annontation注解信息采取不同的处理过程或改变相应程序元素(类、方法及成员变量等)的行为。

例如:Junit、Struts、Spring等流行工具框架中均广泛使用了annontion。使代码的灵活性大提高。

下面自定义一个简单的注解和工具类来演示。

Author注解封装了作者的年龄和姓名。(保持策略需设置为RUNTIME,否则无法通过反射机制获取信息)

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Author {

 long age() default 0L;
 String name() default "unknown";
}

书店类:该类某个方法用Author注解。

public class Bookstore {

 @Author(age = 22, name = "benson")
 public void setBook() {

 }
}

工具类:

import java.lang.reflect.Method;

public class Tool {

 public static void main(String[] args) throws Exception {
  Method[] methods = Class.forName(args[0]).getMethods();
  for(Method method : methods) {
   if(method.isAnnotationPresent(Author.class)) {
    Author author = method.getAnnotation(Author.class);
    printMessage(author);
   }
  }
 }
 
 private static void printMessage(Author author) {
  System.out.printf("Name:%s,Age:%d%n",author.name(),author.age());
 }
}

在调用Java命令时附上参数  "你的包名"+Bookstore  (Eclipse可在Run Configuration里添加参数)

打印结果:

Name:benson,Age:22

这里的核心是用到了Java反射机制。在JDK1.5版本以后,java.lang.reflect包里新增了AnnotatedElement(被注解的元素,即类,方法,字段,构造函数,接口等)。像Class,Constructor,Method,Filed等类都实现了AnnotatedElement接口。该接口的声明如下:

public interface AnnotatedElement {

    boolean isAnnotationPresent(Class<? extends Annotation> annotationClass);  //判断该元素是否被指定的元素注解


    <T extends Annotation> T getAnnotation(Class<T> annotationClass);        //根据给定的注解class返回相应的类


    Annotation[] getAnnotations();                                          //返回指定元素所有的注解,包括继承下来的。如果没有则返回零长度的数组

    Annotation[] getDeclaredAnnotations();                                  //同上,只不过不包括继承的注解
}

相关内容