本文介绍了缩小继承的返回类型(涉及泛型)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在琢磨一些关于在子类化时能够缩小返回类型的奇怪泛型行为。我设法将问题减少到以下一组类:
的有效缩小类型? p>
编辑:将错误更改为警告
解决方案因为我认为你的意思是这样说:
public abstract class AbstractServiceTest< T extends AbstractIndex> {
抽象IService< T>的getService();
}
制作单独的 V 类型变量,而不是添加您的子类无法实现的约束。 :-P
I'm wrestling with a bit of weird generics behavior regarding being able to "narrow" return types when subclassing. I managed to reduce the problem to the following set of classes:
public class AbstractIndex { } public class TreeIndex extends AbstractIndex { } public interface IService<T extends AbstractIndex> { } public interface ITreeService extends IService<TreeIndex> { } public abstract class AbstractServiceTest<T extends AbstractIndex> { abstract <V extends IService<T>> V getService(); } public class TreeServiceTest extends AbstractServiceTest<TreeIndex> { @Override ITreeService getService() { return null; } }The problem is that Java warns when I try to narrow the return type of getService to ITreeService. The warning is
Why is not ITreeService a valid narrowing type for getService?
EDIT: changed error to warning
解决方案Because I think you meant to say this:
public abstract class AbstractServiceTest<T extends AbstractIndex> { abstract IService<T> getService(); }There's no purpose to making the separate V type variable, other than adding constraints that your subclasses can't fulfil. :-P
这篇关于缩小继承的返回类型(涉及泛型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!