-
java注解是
JDK
1.5出现的新特性,可以说注解的出现让广大java程序员的以摆脱xml
配置文件的束缚,经历过xml
配置文件开发的小伙伴们都知道那种绝望。 -
下面我们先自定义一个注解
package com.poplar.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created By poplar on 2019/9/16
* 自定义注解类
*/
@Target(value = ElementType.METHOD)
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Check {
}
- 然后我们再写一个简单的计算器类,里面有加减乘除等方法
package com.poplar.annotation;
/**
* Created By poplar on 2019/9/16
* 计算器类
*/
public class Calculator {
@Check
public void add() {
String hello = null;
hello.toString();
System.out.println("1 + 3=" + (1 + 3));
}
@Check
public void sub() {
System.out.println("1 - 3=" + (1 - 3));
}
@Check
public void mul() {
System.out.println("2 * 3=" + (2 * 3));
}
@Check
public void div() {
System.out.println("9 / 0=" + (9 / 0));
}
public void show() {
System.out.println("hello ~~~~");
}
}
- 现在我梦就可以写一个测试类来测试我们的代码啦
package com.poplar.annotation;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;
/**
* Created By poplar on 2019/9/16
* 测试类
*/
public class TestCheck {
public static void main(String[] args) throws IOException {
//获取字节码文件
Calculator calculator = new Calculator();
Class cls = calculator.getClass();
//获取所有方法
Method[] methods = cls.getMethods();
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("bug.txt"));
//出现异常的次数
int number = 0;
for (Method method : methods) {
//判断当前方法上面是否有此注解
if (method.isAnnotationPresent(Check.class)) {
try {
method.invoke(calculator);
} catch (Exception e) {
number++;
//把异常信息存储到某个文件中
bufferedWriter.write(method.getName() + " 方法出现异常");
bufferedWriter.newLine();//换行
bufferedWriter.write("异常名称: " + e.getCause().getClass().getSimpleName());
bufferedWriter.newLine();//换行
bufferedWriter.write("异常原因: " + e.getCause().getMessage());
bufferedWriter.newLine();//换行
}
}
}
bufferedWriter.write("本次测试共出现【" + number + "】次异常");
bufferedWriter.flush();
bufferedWriter.close();
}
}
- 运行后让我们来看看最后是否如我们所期待的那样
java.lang.reflect.Method的add 方法出现异常
异常名称: NullPointerException
异常原因: null
java.lang.reflect.Method的div 方法出现异常
异常名称: ArithmeticException
异常原因: / by zero
本次测试共出现【2】次异常
- 大家觉得是不是很有意思呢,当然在实际工作中,我们大多数时候都是在使用别人定义好的注解,不过有时候以需要我们自己定义注解来完成某些工作的.
- 比如如果项目中用到AOP的话,可能就需要我们自己定义注解了.
- 代码地址:https://github.com/weolwo/java_web.git