2012-04-09 32 views
2

我想用泛型编码,但似乎无法弄清楚如何避开使用@SuppressWarnings。如何正确编写这个通用而不需要@SuppressWarnings

我有以下几点:

/** 
* Cache to know which pool provided which object (to know where to return object when done) 
*/ 
private Map<Object, ObjectPool<?>> objectPoolCache = new ConcurrentHashMap<Object, ObjectPool<?>>(); 

/** 
* Returns a borrowed pool object to the pool 
* @param o 
* @throws Exception 
*/ 
public void returnToPool(Object o) throws Exception { 
    // safety check to ensure the object was removed from pool using this interfact 
    if(!objectPoolCache.containsKey(o)) 
     throw new IllegalStateException("Object is not in pool cache. Do not know which pool to return object to"); 

    // get the object pool 
    ObjectPool pool = objectPoolCache.remove(o); 

    // return the object to the pool 
    pool.returnObject(o); 
} 

现在,我得到一个警告,ObjectPool pool是原始类型和return语句类型安全警告。

我的概念如下;我正在寻找一个对象/池对的映射,以便我知道从哪个池中检索了一个对象,以便知道要将对象返回到哪个池。

ObjectPool可以是任何类型对象的ObjectPool;不需要特定的超类型。

我试过使用<? extends Object>,但我不完全确定如何使用它而不会导致编译错误。只需用<? extends Object>替换<?>就会遇到一个问题,我的方法使用Object作为参数,这与扩展对象的池不一致。

任何援助将不胜感激。

谢谢!

埃里克

回答

3

这不是没有@SuppressWarnings可行的,只是因为Java的类型系统是没有强大到足以表达你的Map映射T类型的任何对象的一些ObjectPool<? super T>约束。泛型被设计用来证明Java中各种操作的类型安全性,但它们对于你正在做的事不够强大。你只需告诉编译器“相信你知道你在做什么”,这就是@SuppressWarnings的用途。

+0

这几乎是我的想法,但认为也许有更多的泛型洞察力的人会有一个奇特的解决方案。可能不会。 :) – 2012-04-09 16:54:59

1

你不能用Java泛型来做到这一点。但我想知道你的对象池缓存是否应该被聚合为Map<Class<?>, ObjectPool<?>>Map<Object, ObjectPool<?>>

+0

不是 - 因为我需要知道哪个对象是从哪个池中检索的。检索的对象实际上是参数化对象(即:具有泛型),并且每种类型都属于不同的池。因此,将对象类用作关键字不会有帮助。 – 2012-04-09 16:57:38