浅谈java运用注解实现对类中的方法检测的工具
创建自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public@interfaceTest{
}
建立测试类
publicclassUserTest{
@Test
publicvoidtestInsert(){
Useruser=null;
System.out.println(user.getUsername());
}
@Test
publicvoidtestQuery(){
Blogb=newBlog();
b.setTips(newString[]{"技术","java","多线程"});
String[]tips=b.getTips();
System.out.println(tips[3]);
}
@Test
publicvoiddivide(){
System.out.println(10/0);
}
}
编写工具类
publicstaticvoidmain(String[]args){
BufferedWriterbw=null;
try{
//记录方法总数
intmethodCount=0;
//记录错误方法总数
intexpCount=0;
//准备一个文件输出流,用于记录程序执行过程中的异常信息
bw=newBufferedWriter(newFileWriter("log.txt"));
//获取类的Class对象
Classclz=UserTest.class;
//创建目标类型的实例对象
Objectobj=clz.newInstance();
//获取所有的方法对象
Method[]methods=clz.getMethods();
for(Methodm:methods){
if(m.isAnnotationPresent(Test.class)){
//统计总共有多少方法需要被测试
methodCount++;
}
}
bw.write("测试方法总数:"+methodCount);
bw.newLine();
bw.write("================================");
bw.newLine();
for(Methodm:methods){
try{
//如果方法上面包含了Test注解则作为测试方法进行测试
if(m.isAnnotationPresent(Test.class)){
m.invoke(obj);
}
}catch(Exceptione){
//异常方法计数器递增
expCount++;
bw.write(m.getName()+"出现异常");
bw.newLine();
bw.write("类型:"+e.getCause().getClass());
bw.newLine();
bw.write("原因:"+e.getCause().getMessage());
bw.newLine();
bw.write("================================");
bw.newLine();
}
}
bw.write("错误方法总数:"+expCount);
bw.newLine();
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
if(bw!=null){
bw.flush();
bw.close();
}
}catch(IOExceptione){
e.printStackTrace();
}
}
}
到此这篇关于浅谈java运用注解实现对类中的方法检测的工具的文章就介绍到这了,更多相关java运用注解实现对类中的方法检测的工具内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!