java static序列化
阿新 • • 發佈:2020-10-25
https://blog.csdn.net/yangxiangyuibm/article/details/43227457
博主講的很好
package test; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream;public class Main{ public static void main(String[] args){ Person person = new Person(); person.setAge(25); person.setName("YXY"); Person.test="JAVA"; //modify the test value File file = new File("c:/test.txt"); try { OutputStream out= new FileOutputStream(file); ObjectOutputStream objout = new ObjectOutputStream(out); objout.writeObject(person); objout.close(); } catch (IOException e) { e.printStackTrace(); } //code segment 1 Person perobj = null; try { InputStream in = new FileInputStream(file); ObjectInputStream objin = new ObjectInputStream(in); perobj = (Person)objin.readObject(); System.out.println(perobj.test); in.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
正是因為static變數不會被序列化,所以輸出perobj.test時,因為perobj是一個Person型別的變數,所以jvm會到方法區中(jdk1.8之後應該到堆中找到靜態變數)
發現Person型別靜態屬性是“JAVA”,所以打印出"JAVA"
package test; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; public class TEST { public static void main(String[] args){ File file = new File("c:/test.txt"); //code segment 1 Person perobj = null; try { InputStream in = new FileInputStream(file); ObjectInputStream objin = new ObjectInputStream(in); perobj = (Person)objin.readObject(); System.out.println(perobj.test); in.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
這時輸出的就是"IBM",因為沒有改變靜態變數的值。