我有这样两个接口和类:冗余泛型参数
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所是可识别的,我认为这将是巨大的,如果我终于可以用这样的:
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>"
}
谢谢,但我不同意。请看我的编辑。 – sinuhepop 2012-03-13 14:43:08
@sinuhepop,编译器当然可以检查'K'的实际类型与'Identifiable'中的类型参数的类型匹配。不过,你需要*声明* K是一个泛型类型参数(因此,在实例化时传递它的实际值)。这就是语言的工作原理。你是对的,这个知识*理论上可以由编译器推断出来,但现在还不是,现在也不是这样,并且多年以前......如果有的话(不幸的是,Java的发展只是向这个方向发展很慢。 ..)。 –
2012-03-13 14:52:02