相关疑难解决方法(0)

冗余通用参数

我有这两个接口和类:

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;
}
Run Code Online (Sandbox Code Playgroud)

一切都按预期工作.但在我看来,GenericRepository(K)中的第二个泛型参数是多余的.因为我知道MyEntity是一个可识别的,我认为如果我最终能像这样使用它会很棒:

public class MyService {
    private GenericRepository<MyEntity> myEntityRepository;
}
Run Code Online (Sandbox Code Playgroud)

但是我没有成功就尝试了不同的事情.可能吗?如果没有,为什么不呢?

更新:回答一些回复.我认为编译器知道MyEntity中哪种类型是通用的.例如:

public class MyEntityGenericRepository implements GenericRepository<MyEntity, Long> {
    // compiles...
}

public class MyEntityGenericRepository implements GenericRepository<MyEntity, String> {
    // compiler says: "Bound mismatch: The …
Run Code Online (Sandbox Code Playgroud)

java generics

9
推荐指数
1
解决办法
554
查看次数

标签 统计

generics ×1

java ×1