#注解&反射实例

1 对某个类中某些方法的测试

1.1 声明注解

Check.java

Check注解用于标注是否需要测试

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Check {}

Pro.java

/**
 * @author Tang
 */
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Pro {
	String className();//需要执行测试的类
	String checkMethod() default "com.tang.annotation.demo.Check";//测试标注check
}
1.2 编写测试Service
@Service
public class AnnotationService {

    // 将此处的com.tang.annotation.demo.Calculator换成要测试的类
	@Pro(className = "com.tang.annotation.demo.Calculator")
	public void check() throws Exception {
		// 获得字节码
		Class<AnnotationService> cl = AnnotationService.class;
		// 获取当前方法
		Method methodr = cl.getMethod("check");

		// 获取方法上的注解,并得到注解的参数
		Pro pro = methodr.getAnnotation(Pro.class);
		String className = pro.className();
		String checkMethod = pro.checkMethod();

		// 获得用于检查的注解标记
		@SuppressWarnings("unchecked")
		Class<? extends Annotation> checkr = (Class<? extends Annotation>) Class
				.forName(checkMethod);

		// 根据类名获取字节码
		Class<?> clazz = Class.forName(className);
		Object obj = clazz.newInstance();
		// 获得所有方法
		Method[] methods = clazz.getMethods();

		BufferedWriter bw = new BufferedWriter(new FileWriter("bug.txt"));

		// 判断方法上是否有Check注解
		for (Method method : methods) {
			System.out.print("name:" + method.getName());
			if (method.isAnnotationPresent(checkr)) {
				// 有,执行
				System.out.println(" Anno test in!");
				try {
					method.invoke(obj);
				} catch (Exception e) {
					// 捕获异常
					bw.write(method.getName() + "方法");
					bw.newLine();
					bw.write("异常的原因:" + e.toString());
					bw.newLine();
					bw.write("---------------------");
					bw.newLine();
				}
			} else {
				System.out.println(" Anno test out!");
			}
		}
		bw.flush();
		bw.close();
	}
}
1.3 需要测试的类
public class Calculator {

	@Check
	public Integer add(Integer a, Integer b) {
		System.out.println(1+0);
		return a + b;
	}
	
	@Check
	public Integer del(Integer a, Integer b) {
		System.out.println(1-0);
		return a - b;
	}
	
	@Check
	public Integer mul(Integer a, Integer b) {
		System.out.println(1*0);
		return a * b;
	}
	
	@Check
	public Integer dev(Integer a, Integer b) {
		System.out.println(1/0);
		return a / b;
	}
	
}
1.4 测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class AnnotationServiceTest {

	@Autowired
	private AnnotationService service;

    // 执行测试
	@Test
	public void testCheck() throws Exception {
		service.check();
	}

}

执行结果:

name:add Anno test in!
name:mul Anno test in!
name:del Anno test in!
name:dev Anno test in!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值