举个例子直接说明,下面是一个学生对象
import java.io.Serializable;
import lombok.Data;
import com.baomidou.mybatisplus.enums.IdType;
import java.math.BigDecimal;
import java.util.Date;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
@TableName("t_student")
@Data
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
/**id*/
@TableId(value="id", type= IdType.AUTO)
private Integer id;
/**姓名*/
private String name;
/**创建时间*/
private Date cratetime;
/**学费*/
private BigDecimal xuefei;
/**年龄*/
private Integer age;
}
对象要能被序列化必须实现Serializable接口。
序列化
public static byte[] serialize(Object object) {
ObjectOutputStream o= null;
ByteArrayOutputStream b = null;
try {
// 序列化
b = new ByteArrayOutputStream();
o = new ObjectOutputStream(b);
o.writeObject(object);
byte[] bytes = b.toByteArray();
return bytes;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
反序列化
public static Object unserialize(byte[] bytes) {
ByteArrayInputStream b = null;
try {
// 反序列化
b= new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(b);
return ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}