淺談java運用注解實現(xiàn)對類中的方法檢測的工具
更新時間:2020年08月03日 16:55:54 作者:LL_19980115
這篇文章主要介紹了淺談java運用注解實現(xiàn)對類中的方法檢測的工具,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
創(chuàng)建自定義注解
@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 { //記錄方法總數(shù) int methodCount = 0; //記錄錯誤方法總數(shù) int expCount = 0; //準備一個文件輸出流,用于記錄程序執(zhí)行過程中的異常信息 bw = new BufferedWriter(new FileWriter("log.txt")); // 獲取類的Class對象 Class clz = UserTest.class; //創(chuàng)建目標類型的實例對象 Object obj = clz.newInstance(); //獲取所有的方法對象 Method[] methods = clz.getMethods(); for (Method m : methods) { if(m.isAnnotationPresent(Test.class)) { //統(tǒng)計總共有多少方法需要被測試 methodCount++; } } bw.write("測試方法總數(shù):" + methodCount); bw.newLine(); bw.write("================================"); bw.newLine(); for (Method m : methods) { try { //如果方法上面包含了Test注解則作為測試方法進行測試 if(m.isAnnotationPresent(Test.class)) { m.invoke(obj); } } catch (Exception e) { //異常方法計數(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("錯誤方法總數(shù):" + expCount); bw.newLine(); } catch (Exception e) { e.printStackTrace(); }finally { try { if(bw != null) { bw.flush(); bw.close(); } } catch (IOException e) { e.printStackTrace(); } } }
到此這篇關于淺談java運用注解實現(xiàn)對類中的方法檢測的工具的文章就介紹到這了,更多相關java運用注解實現(xiàn)對類中的方法檢測的工具內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java后端對接微信支付(小程序、APP、PC端掃碼)包含查單退款
微信支付我們主要聚焦于這三種支付方式,其中JSPAI與APP主要與uniapp開發(fā)微信小程序與APP對接,本文主要介紹了Java后端對接微信支付(小程序、APP、PC端掃碼)包含查單退款,具有一定的參考價值,感興趣的可以了解一下2021-12-12