有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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;
 }
}

我能做些什么来避免选角吗


共 (4) 个答案

  1. # 1 楼答案

    首先,可以使ICacheable扩展Serializable,这将简化代码


    你能尝试参数化方法add的参数吗

    public class Cache<TKey extends Serializable, 
       TValue extends Serializable & ICacheable >
    {
     ...
     public void add(CacheItem<TKey, TValue> cacheItem)
     {   
      TKey key = cacheItem.getKey();
      TValue value = cacheItem.getValue();
      add(key, value);
     }
    }
    

    因为CacheItem是一个参数化类,所以对它的大多数引用都应该使用参数。 否则,它仍然有未解析的类型,您将面临casts

  2. # 2 楼答案

    我认为你应该像下面这样改变你的课程

    public class Cache<TKey extends Serializable, 
       TValue extends Serializable & ICacheable >
    {
     private Map<Serializable, Serializable> cacheStore = 
         Collections.synchronizedMap(new HashMap<Serializable, Serializable>());
    
     public void add(Serializable key, Serializable value)
     {
      cacheStore.put(key, value);
     }
    
     @SuppressWarnings("unchecked")
    public void add(CacheItem cacheItem)
     {   
      Serializable key = cacheItem.getKey();
      //Do not compiles. Incompatible types. Required: TValue. Found: java.io.Serializable
      Serializable value = 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);
     }
    
    }
    
  3. # 3 楼答案

        public void add(CacheItem<TKey, TValue> cacheItem) {
        TKey key = cacheItem.getKey();
        TValue value = cacheItem.getValue();
        add(key, value);
    }
    
  4. # 4 楼答案

    您正在CacheItem上使用原始类型。试试这个签名:

      public void add(CacheItem<TKey, TValue> cacheItem)
    

    这将要求CacheItem具有与缓存相同的通用参数