我有一个实体的类层次结构,并希望用 Java 为它们创建一个服务接口(interface)的层次结构。然后,UI 组件应通过接口(interface)访问实体相关的服务:
class BaseEntity { }
class Fruit extends BaseEntity { }
class Banana extends Fruit { }
class Apple extends Fruit { }
UI 组件(在略有不同的上下文中在多个位置重用)需要通过 FruitService 接口(interface)访问 Fruit 服务,我想在运行时决定在哪些位置使用 BananaService 或 AppleService 服务接口(interface)。我认为使用泛型会很简单:
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 中的通用参数能够解析为我在 BananaService 中指定的 Banana!
最佳答案
interface FruitService<F extends Fruit> extends Service<Fruit> {}
应该是
interface FruitService<F extends Fruit> extends Service<F> {}
这样,您就可以将泛型传递给服务
关于Java通用接口(interface)层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42976271/