我有一個對象緩存類,可以將對象保存在內存中,當我嘗試稍後檢索它時會出現問題。如何輸出通用對象,然後將其放入另一端的已定義對象中。這裏是類我如何將一般緩存的對象轉換爲具體的android
public class ObjectCache implements Serializable{
private static final long serialVersionUID = 1L;
private Context context;
private String objectName;
private Integer keepAlive = 86400;
public ObjectCache(Context context,String objectName) {
this.context = context;
this.objectName = objectName;
}
public void setKeepAlive(Integer time) {
this.keepAlive = time;
}
public boolean saveObject(Object obj) {
final File cacheDir = context.getCacheDir();
FileOutputStream fos = null;
ObjectOutputStream oos = null;
if (!cacheDir.exists()) {
cacheDir.mkdirs();
}
final File cacheFile = new File(cacheDir, objectName);
try {
fos = new FileOutputStream(cacheFile);
oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (oos != null) {
oos.close();
}
if (fos != null) {
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return true;
}
public boolean deleteObject() {
final File cacheDir = context.getCacheDir();
final File cacheFile = new File(cacheDir, objectName);
return (cacheFile.delete());
}
public Object getObject() {
final File cacheDir = context.getCacheDir();
final File cacheFile = new File(cacheDir, objectName);
Object simpleClass = null;
FileInputStream fis = null;
ObjectInputStream is = null;
try {
fis = new FileInputStream(cacheFile);
is = new ObjectInputStream(fis);
simpleClass = (Object) is.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (is != null) {
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return simpleClass;
}
}
而且從活動一開始對象類,保存它,retreive它像這樣
objectCache = new ObjectCache(this,"sessionCache2");
//save object returns true
boolean result = objectCache.saveObject(s);
//get object back
Object o = objectCache.getObject();
,而不是對象OI需要的是一個Session對象,但隨後即將意味着getObject方法的返回類型需要返回該類型。我不能將對象轉換一些
如果確實已展平並重新分類Session類的對象,那麼應該仍然存在Session類的對象,並且現在還需要對類型對象的引用。 Session類的對象仍然存在。您應該能夠進行顯式強制轉換,以獲取Session類對象的類型爲Session的引用。所以對象有類和引用變量有類型。 http://www.geocities.com/jeff_louie/OOP/oop6.htm – JAL 2011-06-03 02:24:48