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",因为没有改变静态变量的值。