什么是java序列化和反序列化?
序列化的原理是将一个对象转成字节流,使其能被写入到文件中,通过网络传输或者存储在数据库中。反序列化则与其相反。
简而言之,序列化就是将对象转成字节流,反序列化则是将字节流重新恢复成对象。
一个类只有实现了java.io.Serializable接口才有资格进行序列化。
定义Person类:
该类中将nationality声明为transient,所以该参数不会参与序列化操作。
package com.led.javabase; import java.io.Serializable; /** * person entity */ public class Person implements Serializable{ private String name; private int age; private String gender; private transient String nationality;//this field will not take part in serialization public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getNationality() { return nationality; } public void setNationality(String nationality) { this.nationality = nationality; } public Person(String name, int age, String gender, String nationality) { this.name = name; this.age = age; this.gender = gender; this.nationality = nationality; } }
序列化实例:
下面的例子是将一个person实例序列化到Person.ser文件中,通过FileOutputStream和ObjectOutputStream来进行操作的:
package com.led.javabase; import java.io.*; /** * java serialization test * @author Alan */ public class SerializationTest1 { public static void main(String[] args) { Person person = new Person("Jack",11,"male","US"); try { FileOutputStream fos = new FileOutputStream("Person.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(person); oos.close(); fos.close(); System.out.println("Serialization done!"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } } }
控制台输出:
反序列化实例:
下面的例子通过使用FileInputStream和ObjectInputStream来进行反序列化,通过读取Person.ser文件,将字节流转成Person类的对象,
由于Person类的nationality参数声明为了transient,所以该参数不参与序列化化操作,导致反序列化该参数输出为null。
package com.led; import com.led.javabase.Person; import java.io.*; /** * @author Alan * @Description: De-serialization Object * @date 2018/4/22 12:36 */ public class DeSerializtion { public static void main(String[] args) { Person o = null; try { FileInputStream fos = new FileInputStream("Person.ser"); ObjectInputStream ois = new ObjectInputStream(fos); o = (Person) ois.readObject(); ois.close(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return; } catch (IOException e2){ e2.printStackTrace(); return; } catch (ClassNotFoundException e) { e.printStackTrace(); return; } System.out.println("student's name: " + o.getName()); System.out.println("student's age: " + o.getAge()); System.out.println("student's gender: " + o.getGender()); System.out.println("student's nationality: " + o.getNationality()); } }
控制台输出: