標籤:資料庫 annotion 自訂註解
- 定義一個DBinfo 註解
@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)@Inheritedpublic @interface DBinfo { public String URL() ; public String Username() ; public String Password() ; public String Driver() ;}
- 建立DBHelper,實現 getCon方法 注意導包
public class DBHelper { @DBinfo(URL="jdbc:mysql://localhost:3306/test",Username="root",Password="Rindy_RR",Driver="com.mysql.jdbc.Driver") public Connection getCon(String URL,String Username,String Password,String Driver){ Connection con=null; try{ Class.forName(Driver).newInstance(); con=DriverManager.getConnection(URL,Username,Password); } catch (Exception e) { throw new RuntimeException(e); } //直接在控制台輸出,看con是否成功得到 System.out.println(con.toString()); return con; }}
- 解析架構的實現
public class ParseDBinfo { public void parseMethod(Class clazz) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{ Object obj = clazz.newInstance(); Method[] methods=clazz.getDeclaredMethods(); for(Method m:methods){ DBinfo dbinfo=m.getAnnotation(DBinfo.class); if(dbinfo!=null){ String URL=dbinfo.URL(); String Username=dbinfo.Username(); String Password=dbinfo.Password(); String Driver=dbinfo.Driver(); //容錯處理 if(URL!=null && Username!=null && Password!=null && Driver!=null && !URL.equals("") && !Username.equals("") && !Password.equals("") && !Driver.equals("")){ m.invoke(obj, URL,Username,Password,Driver); }else{ System.out.println("參數不可為空!"); } } } }}
- 測試類別
public void testApp() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { ParseDBinfo pb=new ParseDBinfo(); pb.parseMethod(DBHelper.class); }
測試結果:
注意getCon( ) 的參數不要寫錯了,根據自己實際的mysql配置來,其實多寫幾次,還是很好理解的。下一次,自訂個Junit,@Test @Before @After
著作權聲明:本文為博主原創文章,謝謝參考!有問題的地方,歡迎糾正,一起進步。
自訂java註解(二) 實現DBHelper中的getCon( )得到資料庫連接