对象序列化是指将java对象转化成二进制流的过程。反之则是反序列化的过程。java中对象通过实现Serializable借口来实现序列化。序列化需要注意以下几点:
1.静态属性无法进行序列化(静态属性是属于类而非对象)。
2.如果A对象属性包含B对象的引用,则序列化A对象时B对象也会被序列化。
3.若被序列化的对象中包含非序列化的属性,序列化是会报 java.io.NotSerializableException 错误,未被序列化的类要加关键字 transient 修饰。
package com.example.demo;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
public class TestSerilizable{
public static void main(String[] args) throws IOException {
OutputStream fos = new FileOutputStream("D:\\a.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
Person p = new Person();
Cat cat = new Cat("katty",p);
oos.writeObject(cat);
oos.close();
}
}
class Person{
private String name;
public Person() {
// TODO Auto-generated constructor stub
}
public Person(String name) {
this.name=name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Cat implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private Person p;
public Cat() {
// TODO Auto-generated constructor stub
}
public Cat(String name,Person p) {
this.name=name;
this.p=p;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person getP() {
return p;
}
public void setP(Person p) {
this.p = p;
}
}
控制台报如下错误:
Exception in thread "main" java.io.NotSerializableException: com.example.demo.Person
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at com.example.demo.TestSerilizable.main(TestSerilizable.java:16)
p属性加上 transient 修饰:
class Cat implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private transient Person p;
public Cat() {
// TODO Auto-generated constructor stub
}
public Cat(String name,Person p) {
this.name=name;
this.p=p;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person getP() {
return p;
}
public void setP(Person p) {
this.p = p;
}
}
程序正常运行。所以序列化的时候一定要注意哦。