How are constructors called during serialization and deserialization?

前端 未结 6 1408
感情败类
感情败类 2020-11-28 06:16

How are the constructors called during serialization and deserialization

  1. When there is one class implementing serializable?
  2. When there is parent/child
6条回答
  •  粉色の甜心
    2020-11-28 06:32

    First of all at the time of Deserialization no any construtor called, all field's value will be set by reflection.

    If you mark your class as Serializable than JVM set the field's value by reflection at the time of Deserialization and after that JVM looks for it's super class and if that is not marked as Serializable then default constructor will call and then call next super class and so on.

    take a look for this scenario :

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    
    public class Test {
    
        public static void main(String...strings) throws IOException, ClassNotFoundException {
            Employee emp = new Employee();
            emp.companyName = "XYZ";
            emp.employeeName = "ABC";
    
            getSirielization(emp);
            Employee em = (Employee) getDeSirielization();
            System.out.println(em.companyName+" "+em.employeeName);
    
        }
    
        public static void getSirielization(Object object) throws IOException {
    
            File f = new File("/home/server/ironman/serializedFile.txt");
            FileOutputStream fo = new FileOutputStream(f);
            ObjectOutputStream oob = new ObjectOutputStream(fo);
            oob.writeObject(object);
        }
    
        public static Object getDeSirielization() throws IOException, ClassNotFoundException {
    
            File f = new File("/home/server/ironman/serializedFile.txt");
            FileInputStream fo = new FileInputStream(f);
            ObjectInputStream oob = new ObjectInputStream(fo);
            Object object = oob.readObject();
            return object;
        }
    }
    
    class Company {
        String companyName;
    
        public Company() {
            System.out.println("Company-Default");
        }
    
    }
    
    class Employee extends Company implements Serializable {
    
        private static final long serialVersionUID = -3830853389460498676L;
    
        String employeeName;
    
        public Employee() {
    
            System.out.println("hello2");
        }
    }
    

提交回复
热议问题