对象序列化

  最近做一个项目,遇到一些序列化问题,下面记录并分享一下。
  该案例讲解了transient关键字以及如何处理一些不能被序列化的对象。本例挑选了3个比较典型的对象。String、Enum可以被序列化。ByteBuffer无法被序列化。
import java.io.IOException;
import java.io.Serializable;
import java.nio.ByteBuffer;

public class Bean implements Serializable {

	private static final long serialVersionUID = 6383175702324635998L;

	private String name;

	private classtype type;

	private transient ByteBuffer buffer;

	public ByteBuffer getBuffer() {
		return buffer;
	}
	public void setBuffer(ByteBuffer buffer) {
		this.buffer = buffer;
	}
	public enum classtype {
		one, two, three
	};
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public classtype getType() {
		return type;
	}
	public void setType(classtype type) {
		this.type = type;
	}
	public String toString() {
		String bean = "{name:" + this.getName() + ",type:" + this.getType() + "}";
		return bean;
	}

	private void writeObject(java.io.ObjectOutputStream out) throws IOException
	{
		out.writeObject(this.name);
		out.writeObject(this.type);
	}
	
	private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException
	{
		this.name = (String)in.readObject();
		this.type = (classtype)in.readObject();
	}
}


有几点说明如下:
1、serialVersionUID 并不推荐使用default值。具体原因可以google。

2、这里使用了transient,因为ByteBuffer无法被序列化。
private transient ByteBuffer buffer;


3、下面两个方法自定义了序列化实现方式,在本例中有些画蛇添足之意。因为不能被序列化的ByteBuffer内置属性已经被设置为transient了。在实际的序列化过程中已经不会引起错误了。
private void writeObject(java.io.ObjectOutputStream out) throws IOException
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException


可是很多情况下,实际的需求是ByteBuffer也需要被序列化。nio.*下这个ByteBuffer并不能被序列化。
所以修改上述两个方法。
	private void writeObject(java.io.ObjectOutputStream out) throws IOException
	{
		out.writeObject(this.name);
		out.writeObject(this.type);
		out.writeObject(this.buffer != null ? this.buffer.array() : null);
	}
	
	private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException
	{
		this.name = (String)in.readObject();
		this.type = (classtype)in.readObject();
		Object obj = in.readObject();
		if(obj != null)
			this.buffer = ByteBuffer.wrap((byte[])in.readObject());
	}


修改之后 去掉transient关键字,这样该对象内所有内容都可以被序列化了。

你可能感兴趣的:(自己实现,对象序列化)