1)序列化作用
1. 使得java对象能够在网络中传输(也就是说发送方要传输一个java对象,必须对对象序列化,然后转化为二进制字节流,这样才能在网络中传输)
2. 使得java对象能够写入本地文件或数据库中(注意这里指将整个对象放入数据库的一个字段而不是一个表中)
2)序列化方法
1. 让java对象实现Serializable接口,并生成一个序列号
2.实例
class Person implements Serializable
{
private static final long serialVersionUID = 6505041009444688248L;
private String name;
private Date birthday;
private int age;
}
Person person = new Person();
person.setName("xny");
person.setAge(10);
person.setBirthday(new Date());
File file = new File("Person.obj");
if(!file.exists())
System.out.println("file not found");
try
{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
//使用ObjectOutputStream的writeObject()方法将java对象转化为字节流
oos.writeObject(person);
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
Person o = (Person) ois.readObject();
System.out.println(o.getName()+" "+o.getAge()+" "+o.getBirthday());
ois.close();
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
结果为:
xny 10 Sun Aug 24 10:53:05 CST 2014
说明已经将对象存入文件中,且能够成功读出
3)特别注意
1. 如果没有显式定义serialVersionUID,那么会根据类的各种信息计算出一个默认的id,但是不同的编译器生成id的算法都不相同。
2. 从文件中读出对象,是根据serialVersionUID来判断是不是同一个类的对象,如果类的信息改变了,那么生成的id也会改变,但是文件中的id还是根据以前的类信息生成的,这样读的话就会出错。
所以:一定要显式自己定义一个serialVersionUID,并且为private ,static类型的
3.在web开发中,web服务器有可能在运行过程中将对象序列化保存,所以有时候自己定义的类会显示警告