版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qgnczmnmn/article/details/86514481
使用动态代理自定义数据库连接池主要代码如下:
final Connection conn=...;
Connection poxyConn=(Connection) Proxy.newProxyInstance(conn.getClass().getClassLoader(),
conn.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object rtValue=null;
//判断当前方法是不是close方法
if ("close".equals(method.getName())) {
//不能直接关闭,匿名方法访问外部对象,外部对象要定义为final
pool.add(conn);
}else{
rtValue=method.invoke(conn, args);
}
return rtValue;
}
});
使用驱动jar包:mysql-connector-java-5.1.5-bin.jar
当运行时报如下异常:
ClassCastException : $Proxy0 cannot be cast to java.sql.Connection
解决办法:
(1)将驱动jar包更改为:mysql-connector-java-5.0.8-bin.jar
(2)将上述代码中:
Connection poxyConn=(Connection) Proxy.newProxyInstance(conn.getClass().getClassLoader(),
conn.getClass().getInterfaces(), new InvocationHandler() {}
更改为:
Connection poxyConn=(Connection) Proxy.newProxyInstance(conn.getClass().getClassLoader(),
new Class[]{Connection.class}, new InvocationHandler() {}
异常分析:
Class.getInterfaces() 返回的值是一个被该类实现的所有接口的数组,因此返回的数组中必须包含Connection接口才能将代理转化为Connection类型;但在本例中使用Class.getInterfaces()时返回为空数组,因此在使用时引入实现接口可以解决该问题。