说明:小明写了一个Caculator类,里面有一些方法 让我来测试方法是否正确呢 将Check注解放在我要检查的方法之前再编写一个测试类就可以啦!具体的异常信息都会存放在bug.txt文件中。具体代码如下:
一、Check注解:
import javax.xml.bind.Element; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(value = ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Check { }
二、小明写的计算机类
package annotation.itcast.demo; //小明定义的计算器类 public class Calculator { @Check public void add(){ System.out.println("1+0="+(1+0)); } @Check public void sub(){ System.out.println("1-0="+(1-0)); } @Check public void mul(){ System.out.println("1*0="+(1*0)); } @Check public void div(){ System.out.println("1/0="+(1/0)); } public void show(){ System.out.println("希望永远没有bug出现"); } }
三、我写的TestCheck类
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /* 这是一个简单的测试框架 当主方法执行后,会自动执行被检测的所有方法(加了Check注解的方法),判断方法是否有异常,记录到文件中 */ public class TestCheck { public static void main(String[] args) throws Exception { //创建对象 Calculator c = new Calculator(); //获取字节码文件对象 Class cls = c.getClass(); //获取所有方法 Method[] methods = cls.getMethods(); int number =0; BufferedWriter bw = new BufferedWriter(new FileWriter("bug.txt")); for (Method method : methods) { //判断方法上是否有Check注解 if( method.isAnnotationPresent(Check.class)) { //如果有 那么就执行 没有则不执行 try { method.invoke(c); } catch (Exception e) { //捕获异常 // 记录到文件 number++; bw.write(method.getName()+"方法存在异常"); bw.newLine(); bw.write("异常的名称:"+e.getCause().getClass().getSimpleName()); bw.newLine(); bw.write("出现异常的原因"+e.getCause().getMessage()); bw.newLine(); bw.write("-----------------"); bw.newLine(); } } } bw.write("总共出现了"+number+"次异常"); bw.flush(); bw.close(); } }