Custom Serialization Example
This program demonstrates custom serialization logic.
Problem Statement
Write a Java program that customizes serialization of a Student object using writeObject and readObject.
Source Code
| 1 | import java.io.*; |
| 2 | class Student implements Serializable { |
| 3 | int id; transient String password; |
| 4 | Student(int id,String password){ this.id=id; this.password=password; } |
| 5 | private void writeObject(ObjectOutputStream oos) throws IOException { |
| 6 | oos.defaultWriteObject(); |
| 7 | oos.writeObject("ENCRYPTED-"+password); |
| 8 | } |
| 9 | private void readObject(ObjectInputStream ois) throws IOException,ClassNotFoundException { |
| 10 | ois.defaultReadObject(); |
| 11 | password=(String)ois.readObject(); |
| 12 | } |
| 13 | } |
| 14 | public class CustomSerializeExample { |
| 15 | public static void main(String[] args) throws Exception { |
| 16 | System.out.println("Eduinq Custom Serialize Example"); |
| 17 | ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("student.ser")); |
| 18 | Student s=new Student(1,"secret"); |
| 19 | oos.writeObject(s); oos.close(); |
| 20 | ObjectInputStream ois=new ObjectInputStream(new FileInputStream("student.ser")); |
| 21 | Student s2=(Student)ois.readObject(); |
| 22 | System.out.println("Eduinq Student Password: "+s2.password); |
| 23 | } |
| 24 | } |
Program Output
Eduinq Custom Serialize Example Eduinq Student Password: ENCRYPTED-secret
Explanation
Overrides writeObject and readObject. - Adds custom logic for sensitive fields. - Exception handling ensures safe operations. - In enterprise systems, custom serialization secures sensitive data. Conclusion: Shows custom serialization logic.