转换为实现类 [英] Cast to Implemented Class

查看:177
本文介绍了转换为实现类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我使用Java,尝试将 java.sql.ResultSet 转换为我自己的类 MyResultSet

So, I'm working in Java, Trying to cast a java.sql.ResultSet to my own class MyResultSet

以下是代码:
MyResultSet.java

Here is the code: MyResultSet.java

public class MyResultSet implements java.sql.ResultSet{
     //There are a bunch of Implemented Methods here. None of them have any custom code, They are all unchanged. Just didn't want to put huge code in here.
}

我试图使用的代码

ResultSet r = getResultSet();
return (MyResultSet)r;

每当我运行这个,我得到一个ClassCastException。

Whenever I run this, I get a "ClassCastException".

有人可以向我解释如何强制转换为已实现的类吗?

Could someone explain to me how to cast to an Implemented Class?..

推荐答案

getResultSet()会给你一个 java.sql.ResultSet 的实现,这显然是不是你的,但属于Java实现。

You cannot cast. The getResultSet() will give you an implementation of java.sql.ResultSet, which is apparently not yours, but belongs to the Java implementation.

如果要使用您的方法,可以 p>

If you want to use your methods, you can delegate the calls:

public class MyResultSet implements ResultSet{
private ResultSet orig;
public MyResultSet(ResultSet orig) {
    this.orig = orig;
}

// do delegations, 1000 methods like this
public String getString(int columnIndex) throws SQLException {
    return orig.getString(columnIndex);
}
// your own methods can come here
}

在Eclipse中,您可以为委派的方法生成代码,不必逐个编写它们。只需创建私有字段,并执行 RightClick - 源 - 生成代理方法...

In Eclipse, you can generate the code for delegated methods, don't have to write them one by one. Just create the private field, and do RightClick - Source - Generate Delegate Methods...

这种技术称为。你将原始对象包装到你的对象中,添加额外的功能。

This technique is called wrapping. You wrapped the original object into your one, adding extra functionality.

现在您可以调用:

ResultSet originalresultset = ...;
MyResultSet myresultset = new MyResultSet(originalresultset);

这篇关于转换为实现类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆