问题
I have following class which takes an interface and execute some functions:
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();
}
}
The interface is implemented by an abstract class:
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.");
}
}
}
The class (or the interface) which is passed to the handler class extend the abstract class from above:
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;
}
}
The question is whether it is possible to pass the object type (MyObjectData
) of the returned list of the overridden getDataList()
method from the class MSSQLTaskStatement
to the handler class public List<?> getDataList() throws SQLException
method ?
Best Regards, Sandro
回答1:
Add a type parameter <T>
or <T extends ObjectDataBaseClass>
to IMSSQLStatement
and MSSQLStatement
, change the method getDataList in IMSSQLStatement to List<T> getDataList()
and use 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
).
回答2:
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.
来源:https://stackoverflow.com/questions/15270133/specify-object-type-of-a-returned-array-list-dynamically