Java基础21 序列化和反序列化

  1. 网络传输,将对象转换为字节序列在网络中传输

  2. 进程间通信,两个不同的进程可以传递对象

序列化的实现

====================================================================

java.io中的对象流提供了序列化和反序列化对象的方法

对象输出流 ObjectOutputStream

构造方法:

ObjectOutputStream(OutputStream out)

保存对象的方法:

void writeObject(Object obj)

对象输入流 ObjectInputStream

构造方法:

ObjectInputStream(InputStream out)

读取对象方法:

Object readObject()

序列化要注意的地方


  1. 只有实现了Serializable接口的对象,才能序列化,否则会抛出NotSerializableException

  2. 如果父类实现了Serializable接口,子类可以不实现该接口

  3. 类要序列化,类所有的属性也要序列化

  4. 声明为static和transient类型的属性不能被序列化

序列化案例


这个案例演示分别把一头大象和多头大象保存到磁盘文件中。

/**

  • 大象

*/

public class Elephant implements Serializable{

/**

*/

private static final long serialVersionUID = 2483988729860853698L;

private String name;

private Integer age;

private Double weight;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

public double getWeight() {

return weight;

}

public void setWeight(double weight) {

this.weight = weight;

}

public Elephant(String name, int age, double weight) {

super();

this.name = name;

this.age = age;

this.weight = weight;

}

public Elephant() {

super();

}

@Override

public String toString() {

return “Elephont [name=” + name + “, age=” + age + “, weight=” + weight + “]”;

}

public void run(){

System.out.println(name+“在跑!!!!”);

}

}

@Test

public void testObjectOutput(){

//创建对象输出流

try(ObjectOutputStream out = new ObjectOutputStream(

new FileOutputStream(“C:/xpp/object”))){

//存入Java对象

out.writeObject(new Elephant(“非洲大象”,20,5000));

//存入对象集合

List list = Arrays.asList(

new Elephant(“非洲大黑象”,10,10000),

new Elephant(“非洲小黑象”,10,10000),

new Elephant(“亚洲小黑象”,10,10000),

new Elephant(“亚洲大黑象”,10,10000),

new Elephant(“亚洲小白象”,10,10000));

out.writeObject(list);

} catch (IOException e) {

e.printStackTrace();

}

}

@Test

public void testObjectInput(){

//创建对象输入流

try(ObjectInputStream in = new ObjectInputStream(

new FileInputStream(“C:/xpp/object”))){

//读取Java对象

Elephant elephont = (Elephant) in.readObject();

elephont.run();

//读取对象集合

List list = (List) in.readObject();

for(Elephant ele : list){

ele.run();

}

} catch (IOException e) {

e.printStackTrace();

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

}

我们看到无论是一个Java对象,或是一个Java集合都可以序列化到文件中,因为Java所有的集合也都实现了Serializable接口。

serialVersionUID的作用


当一个类实现序列化接口后,IDE会出现编译警告,并提示生成一个serialVersionUID。

也就是类中的常量:

private static final long serialVersionUID = 2483988729860853698L;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值