Annotation的应用场合
annotation一般作为一种辅助途径,应用在软件框架或工具中,在这些工具类中根据不同的 annontation注解信息采取不同的处理过程或改变相应程序元素(类、方法及成员变量等)的行为。
例如:Junit、Struts、Spring等流行工具框架中均广泛使用了annontion。使代码的灵活性大提高。
下面自定义一个简单的注解和工具类来演示。
Author注解封装了作者的年龄和姓名。(保持策略需设置为RUNTIME,否则无法通过反射机制获取信息)
public interface AnnotatedElement { boolean isAnnotationPresent(Class<? extends Annotation> annotationClass); //判断该元素是否被指定的元素注解 <T extends Annotation> T getAnnotation(Class<T> annotationClass); //根据给定的注解class返回相应的类 Annotation[] getAnnotations(); //返回指定元素所有的注解,包括继承下来的。如果没有则返回零长度的数组 Annotation[] getDeclaredAnnotations(); //同上,只不过不包括继承的注解}