java中对象的序列化和反序列化
【對象的序列化和反序列化 】
1.定義:
序列化--將對象寫到一個輸出流中。反序列化則是從一個輸入流中讀取一個對象。類中的成員必須是可序列化的,而且要實現Serializable接口,這樣的類的對象才能被序列化和反序列化。這個接口是一個表示型的接口。serialVersionUID是一個串行化類的通用標示符,反串行化就是使用這個標示符確保一個加載的類對應一個可串行化的對象。
自己指定了serialVersionUID,就可以在序列化后,去添加一個字段,或者方法,而不會影響到后期的還原,還原后的對象照樣可以使用,而且還多了方法可以用。serialVersionUID的生成,可以寫1,也可以寫2,但最好還是按照摘要算法,生成一個惟一的指紋數字,eclipse可以自動生成的,jdk也自帶了這個工具。一般寫法類似于
private static final long serialVersionUID = -763618247875550322L;
2.序列化步驟:
1)創建一個對象輸出流:可以包裝一個其他類型的輸出流。
2)通過對象輸出流的writeObject()寫對象。注意使用類型轉化,轉換為相應的類的對象。
3.反序列化步驟:
1)創建一個對象輸入流:可以包裝一個其他類型的輸出流。
2)通過對象輸出流的readObject()寫對象。
4.什么對象需要被序列化?
序列化的基本想法是完成對實例信息的保證。因為實例信息在運行結束后就消失了。要儲存什么信息呢?一定不是關于方法的信息。
5.使用注意事項:
a.有些屬性處于安全考慮不能被序列化(或者不能被序列化),則用transit修飾,若想進一步控制序列化和反序列化,則類中提供readObject()方法和writeObject()方法,(反)序列化時就會調用自定義的方法。注意這兩個方法不是在java.io.Serializable接口定義的,而是在ObjectInputStream和ObjectOutputStream類中定義的,這兩個類實現ObjectInput 和ObjectOutput兩個接口。下邊是一個可變數組的例子,取自Java in a Nutshell 2rd Edition,它在串行化實現了高效的針對可變數組程度調整的方法:
public class IntList implements Serializable
{
// An array to store the numbers.
private int[] nums = new int[8];
// Index of next unused element of nums[].
private transient int size = 0;
/** Return an element of the array */
public int elementAt(int index) throws ArrayIndexOutOfBoundsException {
if (index >= size) throw new ArrayIndexOutOfBoundsException(index);
else return nums[index];
}
/** Add an int to the array, growing the array if necessary. */
public void add(int x) {
// Grow array, if needed.
if (nums.length == size) resize(nums.length*2);
// Store the int in it.
nums[size++] = x;
}
/** An internal method to change the allocated size of the array. */
protected void resize(int newsize) {
int[] oldnums = nums;
// Create a new array.
nums = new int[newsize];
// Copy array elements.
System.arraycopy(oldnums, 0, nums, 0, size);
}
/** Get rid of unused array elements before serializing the array. */
private void writeObject(ObjectOutputStream out) throws IOException {
// Compact the array.
if (nums.length > size) resize(size);
// Then write it out normally.
out.defaultWriteObject();
}
/** Compute the transient size field after deserializing the array. */
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
// Read the array normally.
in.defaultReadObject();
// Restore the transient field.
size = nums.length;
}
}
b.由于串行化是針對類的實例,也就是對象的,所以static這樣的成員是類相關的,也就不會被串行化。
c.注意,API中一個類一旦被串行化了,那么它的父類都是串行化的。你自己設計的類要是想被串行化,那么其父類要確保都串行化。父類一旦串行化,則子類們都自動實現了串行化。所以內部類和可擴展類不建議串行化。
轉載于:https://www.cnblogs.com/fjhh/p/5370853.html
總結
以上是生活随笔為你收集整理的java中对象的序列化和反序列化的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php页面get方法实现ajax,入门实
- 下一篇: 关于storm0.10.0版本的一个小b