Java中的对象序列化


什么是对象序列化

在Java中,对象序列化指的是将对象用字节序列的形式表示,这些字节序列包含了对象的数据和信息,一个序列化后的对象可以被写到数据库或文件中,并且支持从数据库或文件中反序列化,从而在内存中重建对象;

为什么需要序列化

序列化经常被用于对象的网络传输或本地存储。网络基础设施和硬盘只能识别位和字节信息,而不能识别Java对象。通过序列化能将Java对象转成字节形式,从而在网络上传输或存储在硬盘。

那么为什么我们需要存储或传输对象呢?根据我的编程经验,有如下原因需要将对象序列化(以下原因,我表示没使用过。。。)

  • 一个对象的创建依赖很多上下文环境,一旦被创建,它的方法和属性会被很多其它组件所使用;
  • 一个包含了很多属性的对象创建后,我们并不清楚如何使用这些属性,所以将它们存储到数据库用于后续的数据分析;

顺便也说下,根据我(真正的我)的编程经验,序列化使用情况如下:

  • 网络上的对象传输
  • 使用一些缓存框架的时候,比如ehcache,将对象缓存到硬盘的时候,需要序列化,还有hibernate也会用到;
  • RMI(远程方法调用)

Java序列化例子

以下代码展示了如何让一个类可序列化,对象的序列化以及反序列化;

对象:

package serialization;

import java.io.Serializable;

public class Dog implements Serializable {
    private static final long serialVersionUID = -5742822984616863149L;
    private String name;

    private String color;
    private transient int weight;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    public void introduce() {
        System.out.println("I have a " + color + " " + name + ".");
    }
}

main方法

package serialization;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeDemo {
    public static void main(String[] args) {
        // create an object
        Dog e = new Dog();
        e.setName("bulldog");
        e.setColor("white");
        e.setWeight(5);
        // serialize
        try {
            FileOutputStream fileOut = new FileOutputStream("./dog.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(e);
            out.close();
            fileOut.close();
            System.out.printf("Serialized dog is saved in ./dog.ser");
        } catch (IOException i) {
            i.printStackTrace();
        }
        e = null;
        // Deserialize
        try {
            FileInputStream fileIn = new FileInputStream("./dog.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            e = (Dog) in.readObject();
            in.close();
            fileIn.close();
        } catch (IOException i) {
            i.printStackTrace();
            return;
        } catch (ClassNotFoundException c) {
            System.out.println("Dog class not found");
            c.printStackTrace();
            return;
        }
        System.out.println("\nDeserialized Dog ...");
        System.out.println("Name: " + e.getName());
        System.out.println("Color: " + e.getColor());
        System.out.println("Weight: " + e.getWeight());
        e.introduce();
    }
}

结果打印:

Serialized dog is saved in ./dog.ser
Deserialized Dog ...
Name: bulldog
Color: white
Weight: 0
I have a white bulldog.

本文永久更新链接地址

相关内容