自建连接池异常$Proxy0 cannot be cast to java.sql.Connection

自建连接池异常$Proxy0 cannot be cast to java.sql.Connection

今天在网上看到一个连接池的例子,于是按照所说的自己写了一遍,其构思比较巧妙,使用代理的方法在连接关闭的时候将连接送回连接池中,主要代码如下:

// 使用代理获取连接,确保释放(close)连接后,连接能被送回到连接池中
    public Connection getConnection() throws SQLException {
        // TODO Auto-generated method stub
        if(listConnections.size()>0){
            final Connection conn=listConnections.removeFirst();
            System.out.println("从连接池释放了一个连接");
            return (Connection)Proxy.newProxyInstance(JdbcPool.class.getClassLoader(),conn.getClass().getInterfaces(), new InvocationHandler() {

                public Object invoke(Object proxy, Method method, Object[] args)
                        throws Throwable {
                    // TODO Auto-generated method stub
                    if(!method.getName().equals("close")){
                        return method.invoke(conn, args);
                    }else{
                        //将关闭的连接送回连接池
                        listConnections.add(conn);
                        System.out.println("连接被送回连接池");
                        System.out.println("当前连接池大小为 "+listConnections.size());
                        return null;
                    }
                }
            });
        }else{
            throw new RuntimeException("数据库正忙!");
        }

    }

但是测试的时候却抛异常 
ClassCastException : $Proxy0 cannot be cast to java.sql.Connection 
后来网上查了些资料,发现是在获取代理的时候由于数据库驱动不同造成的。 
应该改成 
return (Connection)Proxy.newProxyInstance(JdbcPool.class.getClassLoader(),new Class[]{Connection.class}, new InvocationHandler() {...} 
可以看到二者的区别是 一个使用了conn.getClass.getInterfaces() 另一个使用了new Class[]{Connection.class} 那么为什么会有这样的差别呢? 
原来是这样的: 
conn.getClass.getInterfaces()的结果与你的数据库驱动有关,驱动不同,其结果也就不同。比如你用mysql的驱动可能这样做可以,但是你在oracle下就可能出问题。conn.getClassInterfaces()返回的是一个Class数组,它的第一个元素必须是一个Connection才能将创建的代理转化为Connection,所以用conn.getClass.getInterfaces()不行,具有太多的不稳定性。那么,既然需要的是一个Connection来转化,那么我们直接给一个Connection就好,这也是为什么我们使用new Class[]{Connection.class}有用的原因了。 
另外还有一个有趣的现象,看下面这段代码

Class[] interfaces = conn.getClass().getInterfaces();
             if(interfaces==null||interfaces.length==0){
                 System.out.println("空的");
             }

我测试发现输出结果是 空的 ,看来获取到的interfaces数组是一个空的数组。如果有朋友一定要用conn.getClass().getInterfaces()这种方法,那么该怎么办呢?可以这么做:

Class[] interfaces = conn.getClass().getInterfaces();
             if(interfaces==null||interfaces.length==0){
                 interfaces = new Class[1];
                 interfaces[0] = Connection.class; 
             }


--------------------- 
作者:请叫我林小李 
来源:CSDN 
原文:https://blog.csdn.net/qq_25237663/article/details/48861209 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值