淺談java運(yùn)用注解實(shí)現(xiàn)對(duì)類中的方法檢測(cè)的工具
創(chuàng)建自定義注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test {
}
建立測(cè)試類
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[] {"技術(shù)","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 {
//記錄方法總數(shù)
int methodCount = 0;
//記錄錯(cuò)誤方法總數(shù)
int expCount = 0;
//準(zhǔn)備一個(gè)文件輸出流,用于記錄程序執(zhí)行過程中的異常信息
bw = new BufferedWriter(new FileWriter("log.txt"));
// 獲取類的Class對(duì)象
Class clz = UserTest.class;
//創(chuàng)建目標(biāo)類型的實(shí)例對(duì)象
Object obj = clz.newInstance();
//獲取所有的方法對(duì)象
Method[] methods = clz.getMethods();
for (Method m : methods) {
if(m.isAnnotationPresent(Test.class)) {
//統(tǒng)計(jì)總共有多少方法需要被測(cè)試
methodCount++;
}
}
bw.write("測(cè)試方法總數(shù):" + methodCount);
bw.newLine();
bw.write("================================");
bw.newLine();
for (Method m : methods) {
try {
//如果方法上面包含了Test注解則作為測(cè)試方法進(jìn)行測(cè)試
if(m.isAnnotationPresent(Test.class)) {
m.invoke(obj);
}
} catch (Exception e) {
//異常方法計(jì)數(shù)器遞增
expCount++;
bw.write(m.getName() + "出現(xiàn)異常");
bw.newLine();
bw.write("類型:" + e.getCause().getClass());
bw.newLine();
bw.write("原因:" + e.getCause().getMessage());
bw.newLine();
bw.write("================================");
bw.newLine();
}
}
bw.write("錯(cuò)誤方法總數(shù):" + expCount);
bw.newLine();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(bw != null) {
bw.flush();
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
到此這篇關(guān)于淺談java運(yùn)用注解實(shí)現(xiàn)對(duì)類中的方法檢測(cè)的工具的文章就介紹到這了,更多相關(guān)java運(yùn)用注解實(shí)現(xiàn)對(duì)類中的方法檢測(cè)的工具內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解SpringBoot健康檢查的實(shí)現(xiàn)原理
這篇文章主要介紹了詳解SpringBoot健康檢查的實(shí)現(xiàn)原理,幫助大家更好的理解和學(xué)習(xí)使用SpringBoot框架,感興趣的朋友可以了解下2021-03-03
MongoDB整合Spring實(shí)例詳細(xì)講解(含代碼)
這篇文章主要介紹了MongoDB整合Spring實(shí)例詳細(xì)講解(含代碼),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-01-01
一文講解如何解決Java中的IllegalArgumentException異常
這篇文章主要給大家介紹了關(guān)于如何解決Java中IllegalArgumentException異常的相關(guān)資料,IllegalArgumentException是Java中的一個(gè)標(biāo)準(zhǔn)異常類,通常在方法接收到一個(gè)不合法的參數(shù)時(shí)拋出,需要的朋友可以參考下2024-03-03
HttpServletResponse亂碼問題_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了HttpServletResponse亂碼問題,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-07-07
IDEA Maven源修改為國(guó)內(nèi)阿里云鏡像的正確方式
為了加快 Maven 依賴的下載速度,可以將 Maven 的中央倉(cāng)庫源修改為國(guó)內(nèi)的鏡像,比如阿里云鏡像,以下是如何在 IntelliJ IDEA 中將 Maven 源修改為阿里云鏡像的詳細(xì)步驟,感興趣的同學(xué)可以參考閱讀一下2024-09-09
Java構(gòu)造器與傳值學(xué)習(xí)總結(jié)
這篇文章主要為大家詳細(xì)介紹了Java構(gòu)造器與傳值學(xué)習(xí)總結(jié),文中示例介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01

