在使用一些特殊框架时,对象序列化是无可避免的,那么,它为什么要序列化?该怎么序列化呢?下面来听小编说道说道。
为什么java对象需要序列化?
1、处理对象流,所谓对象流,指将对象的内容进行流化。程序就能够对流化后的对象进行读写操作,也可以将流化后的对象在网络间传输。
2、为了更好的解决在对对象流进行读写操作时所引发的一系列问题。
序列化怎么实现?
将被序列化的类实现Serializable接口(标记接口),该接口无实现的方法,implements
Serializable只是为了标注该对象是可被序列化的,然后使用一个输出流(如:FileOutputStream)来构造一个ObjectOutputStream(对象流)对象;接着,使用ObjectOutputStream对象的writeObject(Object
obj)方法就可以将参数为obj的对象写出(即保存其状态),要恢复的话则用输入流。
示例:import java.io.*;
import java.util.Date;
public class ObjectSaver
{
public static void main(String[] args) throws Exception
{
/*其中的 D:\\objectFile.obj 表示存放序列化对象的文件*/
//序列化对象
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("D:\\objectFile.obj"));
Customer customer = new Customer("王麻子", 24);
out.writeObject("你好!"); //写入字面值常量
out.writeObject(new Date()); //写入匿名Date对象
out.writeObject(customer); //写入customer对象
out.close();
//反序列化对象
ObjectInputStream in = new ObjectInputStream(new FileInputStream("D:\\objectFile.obj"));
System.out.println("obj1 " + (String) in .readObject()); //读取字面值常量
System.out.println("obj2 " + (Date) in .readObject()); //读取匿名Date对象
Customer obj3 = (Customer) in .readObject(); //读取customer对象
System.out.println("obj3 " + obj3); in .close();
}
}
class Customer implements Serializable
{
private String name;
private int age;
public Customer(String name, int age)
{
this.name = name;
this.age = age;
}
public String toString()
{
return "name=" + name + ", age=" + age;
}
}
以上就是今天的全部内容,更多相关java常见问题及解决方法敬请关注奇Q工具网了解具体。