Java 泛型接口层次结构

3

我有一个实体类的层次结构,希望在Java中为它们创建服务接口的层次结构。然后,UI组件将通过接口访问与实体相关的服务:

class BaseEntity { }
class Fruit extends BaseEntity { }
class Banana extends Fruit { }
class Apple extends Fruit { }

一个UI组件(在不同上下文中被重复使用)需要通过FruitService接口访问Fruit服务,并且我希望在运行时决定在哪些地方使用BananaService或AppleService服务接口。我认为使用泛型会很简单:

interface Service<T extends BaseEntity>
{
   List<T> getAll();
   void save (T object);
   void delete (T object);
}

// More strict interface only allowed for fruits. Referenced by UI component
interface FruitService<F extends Fruit> extends Service<Fruit> {}

// Interface only allowed for bananas
interface BananaService extends FruitService<Banana> {}

class BananaServiceImpl implements BananaService
{
   // Compiler error here because expecting Fruit type:
   @Override
   public List<Banana> getAll()
   {
   }
   ...
}

但是这给我带来了以下编译器错误:

The return type is incompatible with Service<Fruit>.getAll()

Java为什么无法识别已使用Banana进行参数化的实现?我期望在BananaServiceImpl中指定的泛型参数应该解析为Banana,因为我在BananaService中已经指定了。
1个回答

11
interface FruitService<F extends Fruit> extends Service<Fruit> {}

应该是这样

interface FruitService<F extends Fruit> extends Service<F> {}
那样,您将通用内容传递给服务。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接