代碼如下:
Connection proxy = (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(),
Connection.class.getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
if ("close".equals(method.getName())) {
returnConn(conn);
return null;
} else {
return method.invoke(conn, args);
}
}
});
在使用動態(tài)代理增強Connection連接對象的close方法時意荤,我碰到了如題所示的異常级野。通過搜索我發(fā)現這個異常出現的原因在于我使用的mysql數據庫驅動的問題洲胖,由于數據庫驅動不同休傍,Connection.class.getInterfaces()返回的結果也不同搭儒,它返回的是一個Class[]數組沪悲,然而此數組的第一個元素必須是Connection才能把創(chuàng)建的代理類轉為Connection對象获洲,否則就會報錯。
所以這里我們可以采取一個替代方式替換Connection.class.getInterfaces()殿如,即new Class[] { Connection.class }贡珊,這樣無論數據庫驅動是什么版本的驅動,都能保證這個類型轉換不出錯涉馁。