缩小继承的返回类型(涉及泛型) [英] Narrowing return types on inheritance (generics involved)

查看:176
本文介绍了缩小继承的返回类型(涉及泛型)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在琢磨一些关于在子类化时能够缩小返回类型的奇怪泛型行为。我设法将问题减少到以下一组类:

  public class AbstractIndex {
}

public class TreeIndex extends AbstractIndex {
}

public interface IService< T extends AbstractIndex> {
}

公共接口ITreeService扩展IService< TreeIndex> {
}

公共抽象类AbstractServiceTest< T扩展AbstractIndex> {
abstract< V extends IService< T>> V getService();
}

public class TreeServiceTest extends AbstractServiceTest< TreeIndex> {
@Override
ITreeService getService(){
return null;


$ / code>

问题在于,当我尝试缩小时,Java会发出警告返回类型 getService ITreeService 。警告是:
$ b


类型安全性:来自类型TreeServiceTest的getService()的返回类型ITreeService需要未经检查的转换以符合类型V AbstractServiceTest


为什么ITreeService不是 getService ?的有效缩小类型? 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

Type safety: The return type ITreeService for getService() from the type TreeServiceTest needs unchecked conversion to conform to V from the type AbstractServiceTest

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

这篇关于缩小继承的返回类型(涉及泛型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆