【发布时间】:2012-03-13 22:41:37
【问题描述】:
我有这两个接口和类:
public interface Identifiable<T> {
T getId();
}
public interface GenericRepository<T extends Identifiable<K>, K> {
T get(K id);
}
public class MyEntity implements Identifiable<Long> {
private Long id;
public Long getId() {
return id;
}
}
public class MyService {
private GenericRepository<MyEntity, Long> myEntityRepository;
}
这一切都按预期工作。但在我看来,GenericRepository (K) 中的第二个通用参数是多余的。因为我知道 MyEntity 是一个 Identifiable,所以我认为如果我最终可以像这样使用它会很棒:
public class MyService {
private GenericRepository<MyEntity> myEntityRepository;
}
但我正在尝试不同的事情但没有成功。可能吗?如果没有,为什么不呢?
更新:回答一些回复。我认为编译器知道 MyEntity 中的泛型类型。例如:
public class MyEntityGenericRepository implements GenericRepository<MyEntity, Long> {
// compiles...
}
public class MyEntityGenericRepository implements GenericRepository<MyEntity, String> {
// compiler says: "Bound mismatch: The type MyEntity is not a valid substitute for the bounded parameter <T extends Identifiable<K>> of the type GenericRepository<T,K>"
}
【问题讨论】: