我有一個用於將對象保存到磁盤的緩存對象,並且我實現這個的方式導致我不得不使用@SupressWarnings。我不是Java專家,但是這看起來像是一種代碼味道,我想知道是否有一種'更好'的方式來做我在這裏做的事情(例如,當我編寫緩存時以某種方式存儲Type,並閱讀這個值,以便能夠實例化一個特定的類型?)。如何避免必須使用@SuppressWarnings(「unchecked」)?
我的緩存對象看起來像這樣(沒有相關的代碼簡潔,刪除):
/**
* Write object o to cache file
*
* @param cacheName
* @param o
* Serializable object to write to cache
*/
public static void put(String cacheName, Serializable o) throws IOException {
FileOutputStream fos = new FileOutputStream(getHashedFileName(cacheName));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(o);
fos.close();
}
/**
* Get an object from the cache. Caller should use exists() before calling
* here to make sure the cache item exists otherwise Exception will be
* thrown
*
* @param cacheName
* @return Object from cache
*/
public static Object get(String cacheName) throws CacheNotFoundException,
IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream(getHashedFileName(cacheName));
ObjectInputStream ois = new ObjectInputStream(fis);
Object o = ois.readObject();
return o;
}
因爲get()方法可以返回任何類型的對象,我現在必須將它轉換回原來的類型時,我從緩存中讀取。我想知道如果我能避免在第一時間產生的警告:
class somethingDoingSomeWork {
/**
* Save all work done to the cache.
* @throws IOException
*/
public void saveToCache() throws IOException {
Cache.put(getCacheKey(), (MyObject<String>) summary);
}
/**
* Repopulate from cache
*/
@SuppressWarnings("unchecked")
public boolean loadFromCache() throws IOException, CacheNotFoundException,
ClassNotFoundException {
// Code removed, checking for existence of cache, etc.
// Cast required here, and this row generates unchecked warning
summary = (MyObject<String>) Cache.get(getCacheKey());
return true;
}
}
編輯:對於人暗示移動@SuppressWarnings
接近於代碼,註釋只能是聲明線路上使用,所以這不會幫我
也使用泛型幫助,但它似乎將問題轉移到Cache.get()
方法。最好的解決辦法似乎是這樣的:http://www.velocityreviews.com/forums/t499693-how-do-you-prevent-unchecked-cast-warning-when-reading-from-objectinputstream.html
您是否知道您可以使用'@SuppressWarnings(「unchecked」)'作爲語句而不是整個方法? – adarshr
也許你可以使用泛型? – hage
不相關的,但你應該讓你的緩存一個實例,然後使用常規方法,而不是靜態方法。 – Luciano