Java通用接口层次结构
我有一个实体的类层次结构,并希望在Java中为它们创建一个服务接口层次结构。然后,UI组件应通过接口访问实体相关服务:Java通用接口层次结构,java,generics,interface,Java,Generics,Interface,我有一个实体的类层次结构,并希望在Java中为它们创建一个服务接口层次结构。然后,UI组件应通过接口访问实体相关服务: class BaseEntity { } class Fruit extends BaseEntity { } class Banana extends Fruit { } class Apple extends Fruit { } UI组件(在稍微不同的上下文中在多个位置重用)需要通过接口FruitService访问Fruit服务,我想在运行时确定在哪个位置将是Banana
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()
{
}
...
}
接口服务
{
List getAll();
无效保存(T对象);
无效删除(T对象);
}
//更严格的接口只允许水果。由UI组件引用
接口服务扩展服务{}
//接口只允许用于香蕉
接口BanaService扩展了服务{}
类BananaServiceImpl实现BananaService
{
//此处出现编译器错误,因为应为水果类型:
@凌驾
公共列表getAll()
{
}
...
}
但是,这给了我以下编译器错误:
The return type is incompatible with Service<Fruit>.getAll()
返回类型与Service.getAll()不兼容
为什么Java不认识到实现已经用香蕉参数化了?我希望BananaServiceImpl中的泛型参数能够像我在BananaService中指定的那样解析为Banana 接口服务扩展服务{}
interface FruitService<F extends Fruit> extends Service<Fruit> {}
应该是
interface FruitService<F extends Fruit> extends Service<F> {}
接口服务扩展服务{}
这样,您就可以将泛型传递给服务