5

更新解决方案是Java.lang.reflect.Proxy 从调用返回另一个代理导致 ClassCastException 分配

我的测试代码代理java.sql.Connection

我像这样创建我的代理:

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;

当我包装 H2 DB 连接时,这非常有效。

当我尝试包装 MySQL 连接时,Connection返回中的代理转换失败,即使connectionI'm wrapping 的类型是Connection. 例外是:

java.lang.ClassCastException: $Proxy11 cannot be cast to java.sql.Connection

H2 连接的日志行是:

connection is org.h2.jdbc.JdbcConnection, true
proxy is $Proxy9, true

对于 MySQL 连接:

connection is com.mysql.jdbc.JDBC4Connection, true
proxy is $Proxy11, false

发生了什么事,为什么我不能包装 MySQL 数据库连接

4

1 回答 1

1

问题是这一行:

connection.getClass().getInterfaces()

它只是为您提供由您想要代理的类直接实现的接口。如果实现了连接接口 f.eg. 通过 MySql-Connection 类的超类(比如说 AbstractConnection),您的代理将不会实现 Connection 接口。

要解决此问题,请将 Connection-Interface 添加到您的代理应实现的接口数组中。

于 2012-11-27T01:27:03.610 回答