Java序列化常见实现方法代码实例
Java序列化是将Java对象转化为字节流的过程,方便进行Java对象在网络中的传输或者持久化储存。本文将介绍Java序列化的常见实现方法以及代码实例。
Java序列化实现方法
Serializable接口
Java的原生序列化实现采用Serializable接口,它是Java提供的一个标记接口,将一个类实现Serializable接口后,Java运行时系统就能够对该对象进行序列化操作。
示例代码:
import java.io.*;
public class SerializationDemo {
public static void main(String[] args) {
Employee e = new Employee("John Doe", "Manager", 5000);
try {
FileOutputStream fileOut = new FileOutputStream("employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in employee.ser");
} catch (IOException i) {
i.printStackTrace();
}
}
}
class Employee implements Serializable {
public String name;
public String profession;
public int salary;
public Employee(String name, String profession, int salary) {
this.name = name;
this.profession = profession;
this.salary = salary;
}
}
Externalizable接口
Externalizable接口是Java提供的第二种序列化方式,相对于Serializable接口,Externalizable接口强制要求对对象中的所有成员变量进行手动序列化和反序列化操作。
示例代码:
import java.io.*;
public class SerializationDemo {
public static void main(String[] args) {
Employee e = new Employee("John Doe", "Manager", 5000);
try {
FileOutputStream fileOut = new FileOutputStream("employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in employee.ser");
} catch (IOException i) {
i.printStackTrace();
}
}
}
class Employee implements Externalizable {
public String name;
public String profession;
public int salary;
public Employee() {}
public Employee(String name, String profession, int salary) {
this.name = name;
this.profession = profession;
this.salary = salary;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(name);
out.writeObject(profession);
out.writeInt(salary);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
name = (String) in.readObject();
profession = (String) in.readObject();
salary = in.readInt();
}
}
总结
本文介绍了Java序列化的两种常见实现方法及代码示例,其中,Serializable接口是Java原生序列化方式,而Externalizable接口则要求手动序列化所有成员变量。在实际使用中,需根据实际情况进行选择。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java序列化常见实现方法代码实例 - Python技术站