抱歉,不知道谁最能提出这个问题,但我会尝试在这里解释我的问题,我有以下类(class):
public class ReadOnlyTable<T extends Model> implements ReadOnly<T> {
...
protected ReadOnlyTable() {
initTable();
}
protected void reloadDataSource() {
initTable();
}
...
@Override
public ArrayList<T> findAll() {
ArrayList<T> result = null;
try {
long startTime = System.currentTimeMillis();
result = datasource.getAllEntries();
// // Logger.getLogger().write("FindAllQuery time was " + (System.currentTimeMillis() - startTime) + "ms");
} catch (Exception e) {
e.printStackTrace();
return null;
}
return result;
}
假设 T 是“Galaxy”类,然后我尝试使用以下代码循环返回数组中的所有元素
for (Galaxy gal : gDAO.findAll()) {
}
为什么它给我一个错误,需要 Galaxy,但找到了对象??我做错了什么,我有返回类型 ArrayList 而不是 ArrayList
编辑1:
gDAO 是这样定义的
private static GalaxyDAO gDAO = (GalaxyDAO) DAOFactory.get(GalaxyDAO.class);
DAOFactory 看起来像这样
public static <T> T get(Class clazz) {
if (!instanceList.containsKey(clazz)) {
try {
GenericDAO genericDAO = null;
Constructor constructor;
constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true);
genericDAO = (GenericDAO) constructor.newInstance();
instanceList.put(clazz, genericDAO);
return (T)genericDAO;
} catch (NoSuchMethodException ex) {
DebugBuffer.writeStackTrace(DAOFactory.class.getName(), ex);
} catch (SecurityException ex) {
DebugBuffer.writeStackTrace(DAOFactory.class.getName(), ex);
} catch (InstantiationException ex) {
DebugBuffer.writeStackTrace(DAOFactory.class.getName(), ex);
} catch (IllegalAccessException ex) {
DebugBuffer.writeStackTrace(DAOFactory.class.getName(), ex);
} catch (InvocationTargetException ex) {
DebugBuffer.writeStackTrace(DAOFactory.class.getName(), ex);
}
}else{
return (T)instanceList.get(clazz);
}
return null;
}
最后
public class GalaxyDAO extends ReadWriteTable<Galaxy> implements GenericDAO {
是的.. ReadWriteTable 扩展了 ReadOnlyTable
public abstract class ReadWriteTable<T extends Model> extends ReadOnlyTable implements ReadWrite<T> {
public ReadWriteTable() {
super();
}
公认解决方案的附录
我的接口(interface)中有一个错误,导致无法将类型提供给 ReadOnlyTable 查看
public interface ReadWrite<T> extends ReadOnly {
而不是
public interface ReadWrite<T> extends ReadOnly<T> {
修复后我还可以更改以下行
public abstract class ReadWriteTable<T extends Model> extends ReadOnlyTable<T> implements ReadWrite<T> {
最佳答案
gDAO
是你的类的一个实例 ReadOnlyTable<T extends Model>
?它的类型参数是什么(你是如何声明它的)?
必须是Galaxy
,否则无法工作。
更新:现在您发布了更多代码,问题是您必须传递类型参数 Galaxy
上课ReadOnlyTable<T extends Model>
,其中findAll
方法是,否则它不知道 T 是什么,会返回 ArrayList<Object>
.
这一行是问题所在:
public abstract class ReadWriteTable<T extends Model> extends ReadOnlyTable implements ReadWrite<T>
ReadOnlyTable 类还必须接收类型参数:
ReadOnlyTable<T extends Model>
所以该行必须是:
public abstract class ReadWriteTable<T extends Model> extends ReadOnlyTable<T extends Model> implements ReadWrite<T>
关于java - 如何返回通用 ArrayList<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11382643/