java检查方法注释_浅谈java运用注解实现对类中的方法检测的工具

创建自定义注解

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.METHOD)

public @interface Test {

}

建立测试类

public class UserTest {

@Test

public void testInsert() {

User user = null;

System.out.println(user.getUsername());

}

@Test

public void testQuery() {

Blog b = new Blog();

b.setTips(new String[] {"技术","java","多线程"});

String[] tips = b.getTips();

System.out.println(tips[3]);

}

@Test

public void divide() {

System.out.println(10/0);

}

}

编写工具类

public static void main(String[] args) {

BufferedWriter bw = null;

try {

//记录方法总数

int methodCount = 0;

//记录错误方法总数

int expCount = 0;

//准备一个文件输出流,用于记录程序执行过程中的异常信息

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

// 获取类的Class对象

Class clz = UserTest.class;

//创建目标类型的实例对象

Object obj = clz.newInstance();

//获取所有的方法对象

Method[] methods = clz.getMethods();

for (Method m : methods) {

if(m.isAnnotationPresent(Test.class)) {

//统计总共有多少方法需要被测试

methodCount++;

}

}

bw.write("测试方法总数:" + methodCount);

bw.newLine();

bw.write("================================");

bw.newLine();

for (Method m : methods) {

try {

//如果方法上面包含了Test注解则作为测试方法进行测试

if(m.isAnnotationPresent(Test.class)) {

m.invoke(obj);

}

} catch (Exception e) {

//异常方法计数器递增

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 (Exception e) {

e.printStackTrace();

}finally {

try {

if(bw != null) {

bw.flush();

bw.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

到此这篇关于浅谈java运用注解实现对类中的方法检测的工具的文章就介绍到这了,更多相关java运用注解实现对类中的方法检测的工具内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值