0

我有以下类,它接受一个接口并执行一些功能:

public class MSSQLHandler {

    IMSSQLStatement statement;

    public MSSQLHandler(IMSSQLStatement statement) {
        this.statement = statement;
    }

    public void invoke() throws SQLException {
        statement.executeStatement();
    }

    public List<?> getDataList() throws SQLException {
        return statement.getDataList();
    }
}

该接口由一个抽象类实现:

public abstract class MSSQLStatement implements IMSSQLStatement {

    protected Connection conn = null;
    protected ResultSet rs = null;

    protected abstract String createStatement() throws SQLSyntaxErrorException;

    public MSSQLStatement(Connection conn) {    
       this.conn = conn;
    }

    public void executeStatement() throws SQLException {    
       Statement st = conn.createStatement();
       String sql = createStatement();
       if(sql != null) {
          rs = st.executeQuery(createStatement());
       } else {
          throw new SQLException("Method 'createStatement()' has to be implemented.");
       }
    }    
}

传递给处理程序类的类(或接口)从上面扩展抽象类:

public class MSSQLTaskStatement extends MSSQLStatement {

    public MSSQLTaskStatement(Connection conn) {
    super(conn);
    }

    private String projectName = null;

    public void setProjectName(String projectName) {
    this.projectName = projectName;
    }

    protected String createStatement() throws SQLSyntaxErrorException {
      // Create SQL query
    }

    @Override
    public List<MyObjectData> getDataList() throws SQLException {
      // Wrap results into a data object and save it to an array list
      List<MyObjectData> l = new ArrayList<MyObjectData>()
      while(rs.next()) {
         MyObjectData o = new MyObjectData();
         o.setColumn1(rs.getString(1))
         l.add(o);
      }
      return l;
    }
}

问题是是否可以将被覆盖方法MyObjectData的返回列表的对象类型()从类传递给处理程序类方法?getDataList()MSSQLTaskStatementpublic List<?> getDataList() throws SQLException

最好的问候, 桑德罗

4

2 回答 2

1

给and添加类型参数<T>or ,把IMSSQLStatement中的getDataList方法改成and使用。<T extends ObjectDataBaseClass>IMSSQLStatementMSSQLStatementList<T> getDataList()public class MSSQLTaskStatement extends MSSQLStatement<MyObjectData>

Then, if your MSSQLHandler has a field IMSSQLStatement<MyObjectData> statement, its own getDataList() can type-safely return a List<MyObjectData> (or you can make MSSQLHandler generic too, if you want to use it with statements that do not build on MyObjectData).

于 2013-03-07T11:52:32.863 回答
0

Please refer Spring's JdbcTemplate class. There is required functionality that you can use even without using Spring at all. Or you can just use it as a helpful guide to build your own persistent layer implementation.

于 2013-03-07T12:03:59.577 回答