UPDATE solution is Java.lang.reflect.Proxy returning another proxy from invocation results in ClassCastException on assignment
My test code proxies java.sql.Connection
.
I create my proxy like so:
log.info("connection is "+connection.getClass().getName()+", "+
(connection instanceof Connection));
Object proxy = java.lang.reflect.Proxy.newProxyInstance(
connection.getClass().getClassLoader(),
connection.getClass().getInterfaces(),
new MockFailureWrapper(connection));
log.info("proxy is "+proxy.getClass().getName()+", "+
(proxy instanceof Connection));
return (Connection)proxy;
When I wrap an H2 DB connection, this works perfectly.
When I try and wrap a MySQL connection, the cast of the proxy to Connection
in the return fails, even though the connection
I'm wrapping is of type Connection
. The exception is:
java.lang.ClassCastException: $Proxy11 cannot be cast to java.sql.Connection
The log line for an H2 connection is:
connection is org.h2.jdbc.JdbcConnection, true
proxy is $Proxy9, true
And for the MySQL connection:
connection is com.mysql.jdbc.JDBC4Connection, true
proxy is $Proxy11, false
What's going on, and why can't I wrap MySQL DB connections?
The problem is this line:
connection.getClass().getInterfaces()
It just gives you the interfaces that are directly implemented by the class you would like to proxy. If the Connection-interface is implemented f.eg. by a superclass of the MySql-Connection class (lets say AbstractConnection), your proxy will not implement the Connection interface.
To fix this, add the Connection-Interface to the array of interfaces your proxy should implement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With