我有一个对象缓存类,可以将对象保存在内存中,当我尝试稍后检索它时会出现问题。如何输出通用对象,然后将其放入另一端的已定义对象中。这里是类我如何将一般缓存的对象转换为具体的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