淺談java運用註解實現對類中的方法檢測的工具
阿新 • • 發佈:2020-08-04
建立自定義註解
@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運用註解實現對類中的方法檢測的工具內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!