抱歉,不知道谁最好地提出问题,但我会在这里尝试解释我的问题,我有以下课程:
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<T>
编辑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();
}
公认解决方案的附录
我的推断中有一个错误,导致无法将类型提供给 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> {