我正在尝试使用抽象Output类的子类将返回类型与数据库函数调用分开。我遇到了一个问题,其中对于ResultSet,我的抽象方法(getResults)返回类型必须与Date,char,char或字符串不同,但它们都应属于Output类或接口。返回ResultSet的子类需要返回List<Map<String,Object>>
,Date应该返回List<Date>
,字符串List<String>
,等等...
客户代码:
LoadableStatement loadedStatementObject= new LoadableStatement.Builder()
.addParam(new In(2, 111111))
.addParam(new Out(1, OracleTypes.CURSOR))
.addStatement(DBPackage.LOOKUP_RECORD.getStatement())
.load();
Output cursor = new Cursor(loadedStatementObject);
Output.java及其子类中的抽象方法。
public class Output{
//Constructor, fields etc...
public abstract Collection getResults();
}
public class Cursor extends Output {
private List<Map<String, Object>> results;
public Cursor(LoadableStatement statement) {
super(statement);
}
@Override
public Collection getResults() {
//Logic to convert some type of list from DB into a
//List<Map<String,Object>>
return new ArrayList<Map<String, Object>>();
}
}
public class StringResult extends Output {
public StringResult(LoadableStatement statement) {
super(statement);
}
@Override
public Collection getResults() {
//Logic that converts a list from DB into a List<String>
}
}
我该如何完成?
答案 0 :(得分:1)
尝试这样的事情:
public class LoadableStatement {}
public abstract class Output<E> {
//Constructor, fields etc...
public abstract Collection<E> getResults();
public Output(LoadableStatement statement) {
/* Some implementation ... */
}
}
public class Cursor extends Output<Map<String, Object>> {
private List<Map<String, Object>> results;
public Cursor(LoadableStatement statement) {
super(statement);
}
@Override
public Collection<Map<String, Object>> getResults() {
//Logic to convert some type of list from DB into a
//List<Map<String,Object>>
return new ArrayList<>();
}
}
public class StringResult extends Output<String> {
public StringResult(LoadableStatement statement) {
super(statement);
}
@Override
public Collection<String> getResults() {
//Logic that converts a list from DB into a List<String>
return new ArrayList<>();
}
}
答案 1 :(得分:0)
您应该定义Output类的通用版本。具有通用返回类型的通用函数。这是一些示例代码:
public class Output<T>{
//fields and constructor
public T getResults();
}
这里T代表类型,您可以使用任何标识符。
注意:在使用集合时,请记住,集合中不允许使用原语。