1. 程式人生 > >序列化&反序列化

序列化&反序列化

序列化
把物件轉化為位元組序列的過程稱之為物件的序列化
反序列化
序列化反之為反序列化

小知識點
serialVersionUID
當我們制定了serialVersionUID後,相當於為它錄入了一個指紋,下次我們再反序列化的時候就可以輕鬆找到它,哪怕它發生了改動,也沒有關係,因為指紋是唯一的。但當我們沒有指定serialVersionUID的時候,java編譯器會自動給這個class一個摘要演算法,當檔案一旦有改動,為了保證編號唯一UID就會不同,因此當再反序列化的時候就會出現兩個序列化版本號不一致的錯誤

java.io.InvalidClassException: com.etoak.crazy.study.serialization.demo.SerializeUserEntity; local class incompatible: 
stream classdesc serialVersionUID = -4352046751782505246, local class serialVersionUID = 3617424993278848111

Transient關鍵字
被transient關鍵字修飾的屬性不參與序列化

DEMO

建立實體類,密碼被transient修飾

package com.etoak.crazy.study.serialization.demo;

import java.io.Serializable;

public class SerializeUserEntity implements Serializable{

	private static final long serialVersionUID = -4352046751782505246L;
	
	private String id;
	private String userName;
	private transient String userPassword;
	
	
	public SerializeUserEntity() {
		super();
	}
	
	
	public SerializeUserEntity(String id, String userName, String userPassword) {
		super();
		this.id = id;
		this.userName = userName;
		this.userPassword = userPassword;
	}

	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserPassword() {
		return userPassword;
	}
	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}


	@Override
	public String toString() {
		return "SerializeUserEntity [id=" + id + ", userName=" + userName + ", userPassword=" + userPassword + "]";
	}
	
	
}

主方法

package com.etoak.crazy.study.serialization.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.UUID;

public class SerializeDemo {
	
	public static void main(String[] args) {
		
		//序列化
		SerializeUser();
		//反序列化
		Deserialization();
	}
	
	public static void SerializeUser() {
		try {
			ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(new File("user")));
			SerializeUserEntity user =  new SerializeUserEntity(UUID.randomUUID().toString(),"TEST","123456");
			System.out.println("序列化:"+user);
			out.writeObject(user);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void Deserialization() {
		try {
			ObjectInputStream in = new ObjectInputStream(new FileInputStream(new File("user")));			
			SerializeUserEntity user2 = (SerializeUserEntity)in.readObject();
			System.out.println("反序列化:"+user2);
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

結果
在這裡插入圖片描述