Java 物件序列化方法
阿新 • • 發佈:2018-12-27
舉個例子直接說明,下面是一個學生物件
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;
}