对不起,谁知道最好地提出这个问题,但是我将在这里解释我的问题,我有以下课程:
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”类,然后我尝试使用以下代码遍历返回的Array中的所有元素
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();
}
公认解决方案的附录
我的界面有误,无法将Type赋予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类还必须接收type参数:
ReadOnlyTable<T extends Model>
因此,该行必须为:
public abstract class ReadWriteTable<T extends Model> extends ReadOnlyTable<T extends Model> implements ReadWrite<T>