Passing to an embedded class

So, I work in Java, trying to give java.sql.ResultSetmy classMyResultSet

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.
}

The code I'm trying to use to create it

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

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

Can someone explain to me how to apply to an embedded class? ..

+1
source share
3 answers

You cannot quit. getResultSet()will provide you with an implementation java.sql.ResultSetthat, apparently, is not yours , but relates to a Java implementation.

If you want to use your methods, you can delegate 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 - Source - Generate Methodsate Methods...

. , .

:

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

, :

public interface Animal { } // in your case java.sql.ResultSet

public class Dog implements Animal { } // in your case r

public class Cat implements Animal { } // in your case MyResultSet 

Animal a = getAnimal(); // returns a Dog
Cat c = (Cat) a; // ClassCastException - Can't cast a Dog to a Cat.

Dog Cat, , Cat Dog.

+5

, getResultSet() , java.sql.ResultSet, , , . , .

       ResultSet
       /       \
MyResultSet  What getResultSet returns

, , , .

:

  • If you know what returns getResultSet()(I mean the class at the lowest level of inheritance), you can inherit MyResultSet.

  • You have a wrapper class that has a member ResultSetand calls the applicable method on that member. Sort of:

    class MyResultSet
    {
      private ResultSet resultSet;
      public MyResultSet(ResultSet resultSet1) { resultSet = resultSet1; }
      public doSomething() { resultSet.doSomething(); }
    }
    
+3
source

All Articles