java如何在另一个具有相同数据类型参数的泛型类(或接口)中使用泛型类(或接口),而无需强制转换
我需要保持<TKey key, TValue value>
对的缓存类。而且TKey
可以是支持Serializable
接口的任何类,TValue
可以是支持Serializable
和我自己的ICacheable
接口的任何类
还有另一个CacheItem
类保持<TKey key, TValue value>
对。
我希望缓存类具有void add(CacheItem cacheItem)
方法。这是我的代码:
public class Cache<TKey extends Serializable,
TValue extends Serializable & ICacheable >
{
private Map<TKey, TValue> cacheStore =
Collections.synchronizedMap(new HashMap<TKey, TValue>());
public void add(TKey key, TValue value)
{
cacheStore.put(key, value);
}
public void add(CacheItem cacheItem)
{
TKey key = cacheItem.getKey();
//Do not compiles. Incompatible types. Required: TValue. Found: java.io.Serializable
TValue value = (TValue) cacheItem.getValue();
//I need to cast to (TValue) here to compile
//but it gets the Unchecked cast: 'java.io.Serializable' to 'TValue'
add(key, value);
}
}
在另一个文件中:
public class CacheItem<TKey extends Serializable,
TValue extends Serializable & ICacheable>
{
TKey key;
TValue value;
public TValue getValue()
{
return value;
}
public TKey getKey()
{
return key;
}
}
我能做些什么来避免选角吗
# 1 楼答案
首先,可以使
ICacheable
扩展Serializable
,这将简化代码你能尝试参数化方法add的参数吗
因为CacheItem是一个参数化类,所以对它的大多数引用都应该使用参数。 否则,它仍然有未解析的类型,您将面临
casts
# 2 楼答案
我认为你应该像下面这样改变你的课程
# 3 楼答案
# 4 楼答案
您正在CacheItem上使用原始类型。试试这个签名:
这将要求CacheItem具有与缓存相同的通用参数