创建自定义注解
?
|
1
2
3
4
5
|
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test {
}
|
建立测试类
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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);
}
}
|
编写工具类
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
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运用注解实现对类中的方法检测的工具内容请搜索快网idc以前的文章或继续浏览下面的相关文章希望大家以后多多支持快网idc!
原文链接:https://blog.csdn.net/LL_19980115/article/details/107744666
相关文章
猜你喜欢
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-25 80
-
2025-05-29 62
-
2025-05-29 67
-
2025-05-25 99
-
2025-05-29 33
热门评论

