0

我有一个可以将对象保存在内存中的对象缓存类,当我稍后尝试检索它时会出现问题。如何输出通用对象,然后将其放入另一端的已定义对象中。这是课程

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;

}
}

从活动开始,我开始对象类,保存它,然后像这样检索它

objectCache = new ObjectCache(this,"sessionCache2");
//save object returns true
boolean result = objectCache.saveObject(s);

//get object back
Object o = objectCache.getObject();

而不是 Object oi 需要它是一个 Session 对象,但这意味着 getObject 方法的返回类型需要返回它。我不能将对象转换一些吗

4

1 回答 1

2

如果您确定ObjectCache将返回的对象是一个Session对象,您所要做的就是强制转换它:

//get object back
Session session = (Session) objectCache.getObject();

如果方法不返回对象,这将抛出ClassCastException(未选中) 。getObject()Session

于 2011-06-03T02:19:33.303 回答