2017年9月17日 用注解控制运行指定类(junit的原理)

   

java.lang.annotation包提供了很多注释,使用@Target和@Retention则可以控制何时运行指定类
@RetentionPolicy有以下几种:
 
   RetentionPolicy.SOURCE:在源文件中有效(即源文件保留)
   RetentionPolicy.CLASS:在class文件中有效(即class保留)
   RetentionPolicy.RUNTIME::在运行时有效(即运行时保留)
@Target主要有以下几种,在写入的时候可以选择多种
ElementType.METHOD    用于方法
ElementType.TYPE       类型
,ElementType.CONSTRUCTOR   构造函数
ElementType.FIELD     对象
ElementType.PARAMETER   参数
 
 
 
@interface Test 表示自定义了一个注释
 1 package day12.pm;
 2 
 3 import java.lang.annotation.ElementType;
 4 import java.lang.annotation.Retention;
 5 import java.lang.annotation.RetentionPolicy;
 6 import java.lang.annotation.Target;
 7 import java.lang.reflect.Method;
 8 /**
 9  * @Target 注解标注自己定义的注解可以应用在哪些元素上
10  * @Retention 注解标注自己定义的注解何时有效
11  */
12 @Retention(RetentionPolicy.RUNTIME)
13 @Target({ ElementType.METHOD, ElementType.TYPE })
14 @interface Test {
15 }
16 
17 class TestService {
18     @Test
19     public void testSave() {
20         System.out.println("==save==");
21     }
22 
23     @Test
24     public void testUpdate() {
25         System.out.println("==update==");
26     }
27 
28     public void testDelete() {
29         System.out.println("==delete==");
30     }
31 }
32 
33 public class ReflectDemo05 {// Junit framework
34     public static void main(String[] args) throws Exception {
35         // 通过反射执行测试类中的有@Test修饰的方法
36         Class<?> c = Class.forName("day12.pm.TestService");
37         Object test = c.newInstance();
38         Method[] ms = c.getDeclaredMethods();
39         for (Method m : ms) {
40             // 判定方法上有没有Test注解
41             if (m.isAnnotationPresent(Test.class)) {
42                 // 有则执行方法
43                 m.invoke(test);    //等同于((TestService) test).testUpdate() 
44             }
45         }
46     }
47 }

 最后的输出结果就只有加上注释了@Test的save和update方法

posted on 2017-09-17 22:09  Loseheart  阅读(409)  评论(0编辑  收藏  举报