ClassCastException: org.postgresql.jdbc4.Jdbc4Connection 不能转换为 org.postgresql.jdbc4.Jdbc4Connection

0 java postgresql classcastexception jboss7.x

我想得到 PGConnection从 JBOSS AS7 中的 PosgreSQL 连接(数据源 postgresql-9.0-801.jdbc4.jar)

我在使用时遇到了强制转换异常(WrappedConnection)connection。所以现在我使用反射(JDK 1.7):

private static PGConnection getPGConnction(Connection connection) throws SQLException {
    if(connection instanceof PGConnection) {
        return (PGConnection)connection;
    }
    try {
        Class[] parms = null;
        Method method =(connection.getClass()).getMethod("getUnderlyingConnection", parms);
        return (PGConnection) jdbc4Conn;
    } catch ...
Run Code Online (Sandbox Code Playgroud)

并捕获异常

java.lang.ClassCastException: org.postgresql.jdbc4.Jdbc4Connection cannot be cast to org.postgresql.jdbc4.Jdbc4Connection
Run Code Online (Sandbox Code Playgroud)

是同一个班!!!怎么会这样?

kaq*_*qao 6

当一个类不能被强制转换为自身时,如果意味着你有 2 个由不同的类加载器加载的副本。在 web 应用程序中,如果您在应用程序本身和应用程序服务器的库中都有 JDBC 驱动程序 jar,这很容易发生。或者,在 .ear 包装的情况下,在war/WEB-INF/lib和 中ear/lib。确保类路径上只有一个 jar,您将摆脱错误。您可以-verbose:class在启动 Java 时通过以获取有关从何处加载类的更多信息。顺便说一句,你的代码中的反射点是什么?就不能getUnderlyingConnection正常打电话吗?