In the previous tutorial, you learned about Serialization that allows us to store the state of a Java object. All of the properties of the Java object are stored somewhere so that other processes can retrieve it to reuse.
But in reality, sometimes we need some of the attributes of a Java object that are not serialized, meaning that the state of those attributes is not preserved, their value will be the default value at startup when creating Java object.
OK, let’s take a look again the example we made in the tutorial about Serialization in Java.
Now that we have the Student object, we want the age attribute of this object to be not serialized. I will declare Student object as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package com.huongdanjava.javaexample; import java.io.Serializable; public class Student implements Serializable { private static final long serialVersionUID = 1L; private String name; private transient int age; 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; } } |
Now, I will run the code to serialized Student object:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.huongdanjava.javaexample; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class SerializationExample { public static void main(String[] args) { // Create Student object Student student = new Student(); student.setName("Khanh"); student.setAge(30); try ( // Use FileOutputStream to save Student object into a file FileOutputStream fos = new FileOutputStream("E:\\student.txt"); ObjectOutputStream oos = new ObjectOutputStream(fos); ) { oos.writeObject(student); } catch (IOException i) { i.printStackTrace(); } } } |
Then read the student.txt file again:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package com.huongdanjava.javaexample; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; public class DeserializationExample { public static void main(String[] args) { Student student = null; try ( FileInputStream fos = new FileInputStream("E:\\student.txt"); ObjectInputStream oos = new ObjectInputStream(fos); ) { student = (Student) oos.readObject(); } catch (IOException i) { i.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.err.println(student.getName()); System.err.println(student.getAge()); } } |
Result:
You see, the value of the age attribute is no longer 30 as before.