2011-06-03 32 views
0

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

+1

如果确实已展平并重新分类Session类的对象,那么应该仍然存在Session类的对象,并且现在还需要对类型对象的引用。 Session类的对象仍然存在。您应该能够进行显式强制转换,以获取Session类对象的类型为Session的引用。所以对象有类和引用变量有类型。 http://www.geocities.com/jeff_louie/OOP/oop6.htm – JAL 2011-06-03 02:24:48

回答

2

如果您确信该ObjectCache将返回的对象是一个Session对象所有你需要做的就是投它:

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

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

+0

谢谢,我知道这很容易 – Brian 2011-06-03 02:22:32

+1

你可以检查铸造前的类型。像这样:Object o = objectCache.getObject();如果(o Session of Session){Session session =(Session)o; – 2011-06-03 02:25:36

相关问题