Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can proxy some classes but not others

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?

like image 877
Will Avatar asked Nov 12 '22 18:11

Will


1 Answers

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.

like image 72
mbelow Avatar answered Nov 15 '22 12:11

mbelow