现在的位置: 首页 > 综合 > 正文

Annotation牛刀小试

2012年11月12日 ⁄ 综合 ⁄ 共 1329字 ⁄ 字号 评论关闭

Annotation的出现真的是非常惊艳,能把许多繁琐的工作化整为零。那么Annotation到底是怎么工作的呢,那么就亲自编写一个Annotation程序尝试一下就比较清楚了。

下面就演示一个简单的Annotation到底是怎么起作用的:

先定义一个叫Hello的Annotation注解

1 @Retention(RetentionPolicy.RUNTIME)//表示运行时能获取参数
2 @Target({ElementType.METHOD})//表示只能作用在方法上面
3 public @interface Hello {
4 String name() default "hello world!";//能设置默认值
5 }

但是仅仅是这个注解是没什么作用的,还必须有解析器来解析她,下面再来写一个解析器Parser.java:

 1 public class Parser {
2 public static void parser(Object obj){
3 Method[] ms=obj.getClass().getMethods();//取得对象的所有方法
4 for(Method m:ms){//遍历方法
5 if(m.isAnnotationPresent(Hello.class)){//判断方法是否有Hello注解
6 Hello hel=m.getAnnotation(Hello.class);//取得Hello注解中属性的值
7 System.out.println("before……"+hel.name());
8 try {
9 m.invoke(obj, null);//唤醒函数
10 } catch (Exception e) {
11 e.printStackTrace();
12 }
13 System.out.println("after……"+hel.name());
14 }
15 }
16 }
17 }

这样一个完整的annotation注解就完成了,下面来测试一下,先写一个目标类Sample.java:

 1 public class Sample {
2 private String something;
3 public String getSomething() {
4 return something;
5 }
6 public void setSomething(String something) {
7 this.something = something;
8 }
9 @Hello //在此处使用注解
10 public void func(){
11 System.out.println(something);
12 }
13 }

最后运行测试:

1 public class Test {
2 public static void main(String[] args) {
3 Sample sample=new Sample();
4 sample.setSomething("some functions");
5 Parser.parser(sample); //调用解析器进行解析分析
6 }
7 }

控制台打印结果:

before……hello world!
some functions
after……hello world!

Bingo!完成

Spring中运用Annotation控制事务其实是一样的道理,所以Java的反射机制真的是很强大啊

抱歉!评论已关闭.