Are static variables serialized in Serialization process

后端 未结 9 1649
深忆病人
深忆病人 2020-12-04 12:30

I\'m stumbled upon understanding java serialization. I have read in many documents and books that static and transient variables cannot be serialized in Java. We declare a

9条回答
  •  没有蜡笔的小新
    2020-12-04 13:13

    Yes, static variable will be serialized if it is initialized at the time of declaration.

    For example,

    case 1 : without initialization at the time of declaration

    class Person implements Serializable{
    
      public String firstName;
    
      static  String lastName;  
    }
    
    public class Employee {
    
      public static void main(String[] args) {
    
          Person p = new Person();
          p.firstName="abc";
          p.lastName="xyz";
          //to do serialization
    
      }
    
    }
    

    output :

    //after deserialization
    
     firstName= abc
    
     lastName= null
    

    case 2 : with initialization at the time of declaration

    class Person implements Serializable{
    
      public String firstName=="abc";
    
      static  String lastName="pqr";  
    }
    
    public class Employee {
    
      public static void main(String[] args) {
    
          Person p = new Person();
          p.firstName="abc";
          p.lastName="xyz";
          //to do serialization
    
      }
    
     }
    

    output :

    //after deserialization

    firstName= abc
    
    lastName= pqr
    

提交回复
热议问题