【发布时间】:2013-05-30 10:53:58
【问题描述】:
这可能以前以某种形式被问过,但我仍然无法解决它,所以我想我会在这里问集体智慧。我有一个这样的界面 - 我留下了一些 cmets,因为它们可能会有所帮助。
/** Technical note: this generic binding is known as F-bound where class
* T is 'the worked-on class' by Splittable i.e. the implementing class.
*/
interface Splittable <T extends Element & Splittable<T>> {
/** Returns an object of the same class which has been split off at
* the point given.
*/
public T splitOff(double at);
/** Appends the object provided, which must be of the same class, to
* this object.
*/
public void append(T el);
}
那么我正在处理一个我在编译时不知道的元素:
if (el instanceof Splittable) {
if (nextEl.getClass == el.getClass) {
// same class so join them
((Splittable)el).append(nextEl);
}
}
这就是我收到编译器警告的地方 - 未经检查地调用 append(T) 作为原始类型 Splittable 的成员。
在 Element 子类中我都尝试过
SubClassEl extends Element implements Splittable
和
SubClassEl extends Element implements Splittable<SubClassEl>
警告没有区别。
另外,在调用 append() 时,我尝试过
((Splittable)el).splitOff(x).append(nextElement)
但编译器不承认 splitOff 应该返回一个 Splittable,只返回一个 Element。
有什么想法吗?
【问题讨论】:
-
你能告诉我们
Element扩展和实现了什么吗? -
嗨 vikingsteve - 不确定这是否有很大帮助:Element 是我用 getEditState、getHeight 之类的东西编写的抽象类,我认为它与泛型问题无关。不过感谢您的关注!
标签: java generics interface class-hierarchy