I want to get PGConnection
from PosgreSQL connection in JBOSS AS7 (Data source postgresql-9.0-801.jdbc4.jar)
I've got cast exception when used (WrappedConnection)connection
. So now I use reflection (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 ...
and catch exception
java.lang.ClassCastException: org.postgresql.jdbc4.Jdbc4Connection cannot be cast to org.postgresql.jdbc4.Jdbc4Connection
It is the same class!!! How can it be?
When a class can not be cast to itself, if means you have 2 copies loaded by different classloaders. In a webapp, this can easily happen if you have the JDBC driver jar both in the application itself and in the app server's lib. Or, in case of .ear packaging, in both war/WEB-INF/lib
and ear/lib
. Make sure there is only a single jar on the classpath and you will get rid of the error. You can pass -verbose:class
when starting Java to get more information on where the classes are being loaded from. Btw, what is the point of reflection in your code? Can't you just call getUnderlyingConnection
normally?
Per kaqqao's advice , I
So problem is solved
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.