Proxy类,定接口的代理类返回实例的转型问题.

mdog26 2008-03-16 10:23:41
语句:
Connection proxyConn = (Connection)Proxy.newProxyInstance(conn.getClass().getClassLoader(),conn.getClass().getInterfaces(),this);

说明下哦,变量类型:conn -- java.sql.Connection
this -- 本类实现了InvocationHandler接口


错误提示:
java.lang.ClassCastException
at DB.ConnectionHandler.bind(ConnectionHandler.java:16)

如果我用Object o = Proxy.newProxyInstance(conn.getClass().getClassLoader(),conn.getClass().getInterfaces(),this);
打出变量o的地址 显示的是:com.microsoft.jdbc.sqlserver.SQLServerConnection@665753
那么证明 是SQLServerConnection的实例啊,难道不能转型Connection?

help me!
...全文
133 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
mdog26 2008-03-17
  • 打赏
  • 举报
回复
问题已经解决:
把conn.getClass().getInterfaces()替换成interfaces,并在中间加上以下代码
Class[] interfaces =conn.getClass().getInterfaces();
if(interfaces==null||interfaces.length==0)
{
interfaces = new Class[1];
interfaces[0] = Connection.class;
}

原因是:interfaces.length==0
就是说Connection是顶层接口
mdog26 2008-03-16
  • 打赏
  • 举报
回复
o instanceof Connection
不是Connection的实例
sql版本:8.00.760(sp3)

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧