inotgaoshou 发表于 2013-2-1 11:59:33

反射-JUnit4的执行的一般流

JUnit4的执行的一般流程:
a) 首先获得待测试类所对应的Class对象。
b) 然后通过该Class对象获得当前类中所有public方法所对应的Method数组。
c) 遍历该Method数组,取得每一个Method对象
d) 调用每个Method对象的isAnnotationPresent(Test.class)方法,判断该方法是否被Test注解所修饰。
e) 如果该方法返回true,那么调用method.invoke()方法去执行该方法,否则不执行。
 

import java.lang.annotation.Annotation;import java.lang.reflect.Method;public class MyReflection{public static void main(String[] args) throws Exception{MyTest myTest = new MyTest();Class<MyTest> c = MyTest.class;Method method = c.getMethod("output", new Class[]{});if(method.isAnnotationPresent(MyAnnotation.class)){method.invoke(myTest, new Object[]{});MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);String hello = myAnnotation.hello();String world = myAnnotation.world();System.out.println(hello + ", " + world);}Annotation[] annotations = method.getAnnotations();for(Annotation annotation : annotations){System.out.println(annotation.annotationType().getName());}}}
页: [1]
查看完整版本: 反射-JUnit4的执行的一般流