About the exception java.lang.ClassCastException:com.sun.proxy using the dynamic proxy handwriting database connection pool. $Proxy 0 cannot is cast to java.sql.Connection

Source: Internet
Author: User

The code is as follows :

FinalConnection Conn=pool.remove (0); //transforming the Close method with dynamic agentsConnection proxy= (Connection) proxy.newproxyinstance (Conn.getclass (). getClassLoader (), Conn.getclass (). Getinterfaces (),NewInvocationhandler () {@Override Publicobject Invoke (Object proxy, Method method, object[] args)throwsThrowable {if("Close". Equals (Method.getname ())) {                        //for the Close method we want to transform, we write ourselvesRetconn (conn); return NULL; }Else{                        //for methods that do not want to be reformed, use the same method as the agent                        returnMethod.invoke (conn, args); }                }            });

Exceptions are as follows:

Java.lang.ClassCastException:com.sun.proxy. $Proxy 0 cannot is cast to java.sql.Connection

Cause Analysis:

The reason for this anomaly is that I am using a MySQL database-driven problem, because the database driver is different, Connection.class.getInterfaces () returns a different result, it returns a class[] array, However, the first element of this array must be connection to convert the created proxy class to the connection object, otherwise it will be an error.

So here we can take an alternative way to replace Connection.class.getInterfaces (), which is new class[] {Connection.class}, so that no matter what version of the database driver it is, Will ensure that this type conversion is not error-prone.

Reference article: dot me

Do me a little harder!

About the exception java.lang.ClassCastException:com.sun.proxy using the dynamic proxy handwriting database connection pool. $Proxy 0 cannot is cast to java.sql.Connection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.