Far*_*ill 2 java generics interface
我有一个实体的类层次结构,并希望在Java中为它们创建服务接口的层次结构.然后,UI组件应通过接口访问与实体相关的服务:
class BaseEntity { }
class Fruit extends BaseEntity { }
class Banana extends Fruit { }
class Apple extends Fruit { }
Run Code Online (Sandbox Code Playgroud)
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()
{
}
...
}
Run Code Online (Sandbox Code Playgroud)
但是这给了我以下编译器错误:
The return type is incompatible with Service<Fruit>.getAll()
Run Code Online (Sandbox Code Playgroud)
为什么Java不认识到实现已经使用Banana进行参数化?我希望BananaServiceImpl中的泛型参数可以像我在BananaService中指定的那样解析为Banana!
interface FruitService<F extends Fruit> extends Service<Fruit> {}
Run Code Online (Sandbox Code Playgroud)
应该
interface FruitService<F extends Fruit> extends Service<F> {}
Run Code Online (Sandbox Code Playgroud)
这样,您将泛型传递给服务
归档时间: |
|
查看次数: |
156 次 |
最近记录: |