@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @interface DBinfo {
public String URL() ;
public String Username() ;
public String Password() ;
public String Driver() ;
}
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( )得到数据库连接
原文地址:http://blog.csdn.net/emilyrr/article/details/47345777