相当尴尬地问这个问题可能很简单,但似乎找不到答案。
我有一个可缓存的接口(interface)
/**
K denotes the type of the key of a cacheable object
*/
public interface Cacheable<K extends Serializable> extends Serializable{
K getKey();
}
然后我有一个存储可缓存内容的缓存
/**
Cache that can store an object of type T and it's key which is of type K
*/
public interface Cache<K, T extends Cacheable>{
Optional<T> get(K key);
T put(T cacheable);
}
虽然这可行,但我希望它能更好,因为上面没有表达 T 和 K 之间的关系。换句话说,这里没有强制执行 T.getKey 应该返回 K 的事实。
下面的内容是我一直在寻找的内容,但显然它是不可编译的。想知道我该怎么做吗?
public interface Cache<K, T<K> extends Cacheable<K>>
最佳答案
在 Java 中你不能拥有高阶泛型(这就是你的 T<K>
技巧无法编译的原因),但你可以拥有受其他泛型约束的泛型。我相信您正在寻找
public interface Cache<K, T extends Cacheable<K>>
关于Java 泛型 - 两个类型参数之间的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72877984/