可以代理某些类而不代理其他类

时间:2012-11-09 10:00:24

标签: java reflection

更新 解决方案为Java.lang.reflect.Proxy returning another proxy from invocation results in ClassCastException on assignment

我的测试代码代理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失败,即使我connection包裹的类型为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数据库连接

1 个答案:

答案 0 :(得分:1)

问题在于这一行:

connection.getClass().getInterfaces()

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

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

相关问题