目录
2.1 注解类(自定义):StartTag.java, EndTag.java, MyTag.java
1. 编码要求
(1)编写代码,设计三个注解@StartTag, @EndTag, @MyTag, 实现类似于junit4的@Before, @After, @Test功能
(2)运用到注解的定义,反射,模板方法等知识点。
2. 示例代码
2.1 注解类(自定义):StartTag.java, EndTag.java, MyTag.java
(1)StartTag.java
package MyStartAndEndTag;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface StartTag {
}
(2)EndTag.java
package MyStartAndEndTag;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface EndTag {
}
(3)MyTag.java
package MyStartAndEndTag;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyTag {
}
2.2 测试类:TestTag.java
package MyStartAndEndTag;
public class TestTag {
@StartTag
public void start(){
System.out.println("before the testing...");
}
@EndTag
public void end(){
System.out.println("after the testing...");
}
@MyTag
public void test1(){
System.out.println("test1");
}
@MyTag
public void test2(String p_str){
System.out.println("test2");
}
@MyTag
public void test3(){
System.out.println("test3");
}
}
2.3 入口类:MyDemo.java
package MyStartAndEndTag;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MyDemo {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?> clazz = Class.forName("MyStartAndEndTag.TestTag");
Object obj = clazz.getDeclaredConstructor().newInstance();
Method[] methods = clazz.getDeclaredMethods(); //获取声明的所有方法,数组存放
int start = -1;
int end = -1;
for (int i=0; i<methods.length; i++){
if(methods[i].getAnnotation(StartTag.class) != null && methods[i].getParameterCount() == 0){
start = i; //找出带有StartTag标签的方法是第几个
break;
}
}
for (int i=0; i<methods.length; i++){
if(methods[i].getAnnotation(EndTag.class) != null && methods[i].getParameterCount() == 0){
end = i; //找出带有EndTag标签的方法是第几个
break;
}
}
//System.out.println("start: " + start);
//System.out.println("end: " + end);
for(int i=0; i<methods.length; i++){
if (methods[i].getAnnotation(MyTag.class) != null && methods[i].getParameterCount() == 0 ){
System.out.println("测试用例名称为: " + methods[i].getName());
//模板方法在用例之前执行
if(start != -1){
methods[start].invoke(obj);
}
//执行用例
methods[i].invoke(obj);
//模板方法在用例之后执行
if(end != -1){
methods[end].invoke(obj);
}
}
}
}
}
输出结果:
测试用例名称为: test3
before the testing...
test3
after the testing...
测试用例名称为: test1
before the testing...
test1
after the testing...