5

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?

Community
  • 1
  • 1
Will
  • 73,905
  • 40
  • 169
  • 246
  • Show us the `Exception`/`Error` you get please. – Adam Arold Nov 09 '12 at 10:07
  • @AdamArold classic CastCastException; added it to the question – Will Nov 09 '12 at 10:08
  • What do you see if you debug your code at the return statement? What type does `proxy` have? – Adam Arold Nov 09 '12 at 10:12
  • @AdamArold proxy is an anonymous class of some sort, created dynamically by Java's reflection; I've printed tried to clarify in the logging in the question – Will Nov 09 '12 at 10:25
  • 1
    possible duplicate of [Java.lang.reflect.Proxy returning another proxy from invocation results in ClassCastException on assignment](http://stackoverflow.com/questions/2642700/java-lang-reflect-proxy-returning-another-proxy-from-invocation-results-in-class) – Will Nov 09 '12 at 11:01

1 Answers1

1

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.

mbelow
  • 1,093
  • 6
  • 11