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