冗余通用参数 [英] Redundant generic parameters
问题描述
我有这两个接口和类:
I have this two interfaces and classes:
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是一个可识别的,我认为如果我最终能够像这样使用它会很棒:
It all works as desired. But in my opinion second generic parameter in GenericRepository (K) is redundant. Because I know that MyEntity is an Identifiable, I think it would be great if I can finally use it like this:
public class MyService {
private GenericRepository<MyEntity> myEntityRepository;
}
但是,我尝试了各种不成功的事情。可能吗?如果没有,为什么不呢?
But I'm trying different things without succeeding. Is it possible? If not, why not?
更新:回答一些回复。我想编译器知道哪些类型是MyEntity中的通用类型。例如:
UPDATE: Answering some responses. I think compiler knows something about which type is the generic in MyEntity. For example:
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>"
}
推荐答案
我不认为你可以省略它。使用 T扩展可识别的< K>
,您想要说通用类型参数必须是可识别
。由于 Identifiable
是一个泛型类,所以您也需要提及它的泛型类型参数(如果您想按照以下规则进行操作 - 如果您忽略它,则会失去所有泛型由于向后兼容性规则,对 GenericRepository
>类型安全性)。另请注意, K
实际上用作 GenericRepository.get
的参数类型。由于该类型可能与 T
不同,因此您需要通过将其声明为另一个通用类型参数 GenericRepository
。否则,编译器无法知道 K
是什么。
I don't think you can omit it. With T extends Identifiable<K>
you want to say that the generic type parameter must be an Identifiable
. Since Identifiable
is a generic class, you need to mention its generic type parameter too (if you want to play by the rules that is - if you omit it, you lose all generic type safety for GenericRepository
, due to backward compatibility rules). Note also that K
is actually used as the parameter type of GenericRepository.get
. And since that type may be different from T
, you need to satisfy the compiler by declaring it as another generic type parameter of GenericRepository
. Otherwise the compiler has no way of knowing what K
is.
这篇关于冗余通用参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!