设为首页 加入收藏

TOP

Annotation的应用场合
2014-11-24 08:10:14 来源: 作者: 【 】 浏览:0
Tags: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 getAnnotation(Class annotationClass); //根据给定的注解class返回相应的类



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


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


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇利用Android的传感器改变背景颜色 下一篇使用C和Shell实现远程Tomcat的重..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·About - Redis (2025-12-26 08:20:56)
·Redis: A Comprehens (2025-12-26 08:20:53)
·Redis - The Real-ti (2025-12-26 08:20:50)
·Bash 脚本教程——Li (2025-12-26 07:53:35)
·实战篇!Linux shell (2025-12-26 07:53:32)