对象序列化

最近做一个项目,遇到一些序列化问题,下面记录并分享一下。
该案例讲解了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关键字,这样该对象内所有内容都可以被序列化了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值