轉載請保留出處: http://blog.csdn.net/xiaxl/article/details/60114057
Serializable用法serialVersionUID的作用Android中,使用Serializable方式將對象序列化到數據庫代碼舉例
Serializable用于實現java對象序列化和反序列化。 序列化可以將一個java對象以二進制流的方式持久化到數據庫、文件中; 反序列化則是可以把之前持久化在數據庫或文件中的二進制數據,以流的方式讀取出來重新構造成一個和之前相同內容的java對象。
代碼舉例說明
public class SnsBiLogData implements Serializable { PRivate static final long serialVersionUID = 1L; public String time; public String event; //string 事件名 public String ip;//string 訪問ip地址 public String network;//string wifi、3G等 public String app_version;//string app版本 public String Operator;//string 運營商}// 序列化工具類public class SerializeUtil { /** * 序列化對象 * * @throws IOException */ public static byte[] serializeObject(Object object) { ByteArrayOutputStream saos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(saos); oos.writeObject(object); oos.flush(); return saos.toByteArray(); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 反序列化對象 * * @throws IOException * @throws ClassNotFoundException */ public static Object deserializeObject(byte[] buf) { ByteArrayInputStream sais = new ByteArrayInputStream(buf); try { ObjectInputStream ois = new ObjectInputStream(sais); return ois.readObject(); } catch (Exception e) { e.printStackTrace(); } return null; }}一種是private static final long serialVersionUID = 1L; 一種根據類名、接口名、成員方法及屬性等來生成一個64位的哈希字段。比如:private static final long serialVersionUID = -8940196742313994740L;
By default, this identifier is computed by hashing the class declaration and its members. This identifier is included in the serialized form so that version conflicts can be detected during deserialization. If the local {@code serialVersionUID} differs from the {@code serialVersionUID} in the serialized data, deserialization will fail with an {@link InvalidClassException} 默認情況下,serialVersionUID是根據類名、接口名、成員方法及屬性等來生成一個64位的哈希字段。對象在反序列化時,serialVersionUID值不同,會拋出InvalidClassException異常,造成反序列化失敗。 
因此,無論serialVersionUID采用的哪一種寫法,只要其在對象序列化與反序列化過程中保持不變即可。
新聞熱點
疑難解答