Java注解和反射
根据 https://blog.csdn.net/qq1404510094/article/details/80577555 这篇博客里的案例 自己敲了一遍 做个记录。
需要被测试的方法都写上了Test注解,检测方法是否有异常。
public class Calculation {
@Test
public void add(){
System.out.println("add result: " + (1 + 0));
}
@Test
public void sub(){
System.out.println("sub result: " + (1 - 0));
}
@Test
public void mul(){
System.out.println("mul result: " + (1 * 0));
}
@Test
public void div(){
System.out.println("div result: " + (1 / 0));
}
}
Test注解
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {
}
测试方法Att
import java.lang.reflect.Method;
public class Att {
public static void main(String[] args) {
Calculation calculation = new Calculation();
Class clas = calculation.getClass();
Method[] methods = clas.getDeclaredMethods();
int errorNum = 0;
StringBuilder errorText = new StringBuilder();
for(Method m : methods){
if(m.isAnnotationPresent(Test.class)){
m.setAccessible(true);
try{
m.invoke(calculation);
}catch (Exception e){
errorNum++;
errorText.append("\n\r");
errorText.append(m.getName());
errorText.append(" ");
errorText.append("hava error");
errorText.append("\n\r cause by ");
errorText.append(e.getCause().getClass().getSimpleName());
errorText.append("\n\r");
errorText.append(e.getCause().getMessage());
errorText.append("\n\r");
}
}
}
errorText.append(clas.getSimpleName());
errorText.append(" has: ");
errorText.append(errorNum);
errorText.append(" error.");
System.out.println(errorText.toString());
}
}
打印结果
add result: 1
sub result: 1
mul result: 0
div hava error
cause by ArithmeticException
/ by zero
Calculation has: 1 error.