關於利用動態代理手寫資料庫連接池的異常 java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to java.sql.Connection

來源:互聯網
上載者:User

標籤:

代碼如下:

final Connection conn=pool.remove(0);                        //利用動態代理改造close方法    Connection  proxy= (Connection) Proxy.newProxyInstance(conn.getClass().getClassLoader(), conn.getClass().getInterfaces(), new InvocationHandler() {                                @Override                public Object invoke(Object proxy, Method method, Object[] args)                        throws Throwable {                    if("close".equals(method.getName())){                        //對於想改造的close方法,我們自己寫                        retConn(conn);                        return null;                    }else{                        //對於不想改造的方法,用被代理者身上相同的方法                        return method.invoke(conn, args);                    }                }            });

異常如下:

 

java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to java.sql.Connection

 

原因分析:

這個異常出現的原因在於我使用的mysql資料庫驅動的問題,由於資料庫驅動不同,Connection.class.getInterfaces()返回的結果也不同,它返回的是一個Class[]數組,然而此數組的第一個元素必須是Connection才能把建立的代理類轉為Connection對象,否則就會報錯。

所以這裡我們可以採取一個替代方式替換Connection.class.getInterfaces(),即new Class[] { Connection.class },這樣無論資料庫驅動是什麼版本的驅動,都能保證這個類型轉換不出錯。

參考文章:點我呀

使勁點我呀

關於利用動態代理手寫資料庫連接池的異常 java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to java.sql.Connection

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.