JAVA Serializable 实例

来源:互联网 发布:开放源代码的软件 编辑:程序博客网 时间:2024/06/05 04:59

1、什么是序列化和反序列化
Serialization(序列化)是一种将对象以一连串的字节描述的过程;反序列化deserialization是一种将这些字节重建成一个对象的过程。

2、什么情况下需要序列化
a)当你想把的内存中的对象保存到一个文件中或者数据库中时候;
b)当你想用套接字在网络上传送对象的时候;
c)当你想通过RMI传输对象的时候;

3、如何实现序列化

将需要序列化的类实现Serializable接口就可以了,Serializable接口中没有任何方法,可以理解为一个标记,即表明这个类可以序列化。

原始api

public interface Serializable
Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.
To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype’s public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class’s state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime.

During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream.

When traversing a graph, an object may be encountered that does not support the Serializable interface. In this case the NotSerializableException will be thrown and will identify the class of the non-serializable object.

Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:

//序列化对象进行输出(转化为Object流)
private void writeObject(java.io.ObjectOutputStream out)
throws IOException
//反序列化用到
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;
private void readObjectNoData()
throws ObjectStreamException;

实例:(以存储文件为例)

创建序列化对象

package com.frank.serializable;import java.io.Serializable;public class People implements Serializable{    private int id;    private String name;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public People(int id,String name){        this.id = id;        this.name = name;    }}

Test类:

package com.frank.serializable;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutput;import java.io.ObjectOutputStream;public class SerializableTest {    public static void seria(People people) throws IOException{        ObjectOutputStream objectOutput=null;        try {            objectOutput=new ObjectOutputStream(new FileOutputStream("D:\\out.txt"));            objectOutput.writeObject(people);        } catch (FileNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }finally{            System.out.println("we have serialized the object");            objectOutput.flush();            objectOutput.close();        }    }    public static People deSeria() throws IOException{        ObjectInputStream objectInputStream=null;        People people=null;        try {            objectInputStream=new ObjectInputStream(new FileInputStream("D:\\out.txt"));            people=(People)objectInputStream.readObject();        } catch (Exception e) {            // TODO: handle exception        }finally{            System.out.println(people.getId()+","+people.getName());            objectInputStream.close();        }        return people;    }    public static void main(String[] args) throws IOException {        // TODO Auto-generated method stub        People people = new People(21,"frank");        SerializableTest.seria(people);//      SerializableTest.deSeria();    }}

运行序列化对象,查看文件

这里写图片描述

序列化对象输出的为字节 记事本打开乱码 正常

反序列化:

这里写图片描述