【发布时间】:2016-05-18 19:22:57
【问题描述】:
我有一个带有泛型 (T1) 的抽象类,它扩展了我的 Filterable 接口:
public abstract class AbstractAdapter < T1 extends Filterable, T2 extends AbstractAdapter.Cell > extends ArrayAdapter < T1 > {
public abstract class Cell {
public T1 info;
//...
}
public abstract void setData(T2 cell, int position);
//...
}
我有具体的类和方法(setData)和单元类实现:
public class ConcreteAdapter extends AbstractAdapter < InfoClass, ConcreteAdapter.Cell > {
public class Cell extends AbstractAdapter.Cell {
//...
}
@Override
public void setData(Cell cell, int position) {
InfoClass info = (InfoClass)cell.info; // need to cast from Filterable to InfoClass (why?). Or i have compilation error
}
//...
}
所以,我有 ConcreteAdapter 类,第一个泛型类为 InfoClass(扩展了 Filterable),在方法 setData 我有 Cell 类对象,但字段“info”我认为是 Filterable,而不是 InfoClass。我认为,字段“info”已经应该是泛型类型,因为它声明为
T1 信息;
但不是
可过滤信息;
是否可以将字段类型从可扩展类更改为通用类而不进行强制转换?还是 IDE 中的错误?
【问题讨论】:
-
假设可以传递给
ConcreteAdapter.setData的唯一Cell对象是ConcreteAdapter.Cell是错误的。如果我对静态类型为AbstractAdapter的对象进行虚拟调用并传入不同的Cell对象怎么办? -
@aioobe,你是对的,但在我的情况下,这些具体的适配器使用本地化并且它们彼此隔离。
-
编译器不知道这一点。
标签: java generics abstract-class