黑马程序员技术交流社区

标题: 对象的序列号疑问 [打印本页]

作者: leon_hm    时间: 2014-3-29 16:04
标题: 对象的序列号疑问
以下是看毕姥爷的视频第21天的时候的代码。运行结果是
lisi:0:kr

而视频中的结果是
lisi:0:cn

为什么我的结果不一样呢?

  1. import java.io.*;
  2. class ObjectStreamDemo
  3. {
  4.         public static void main(String[] args) throws Exception
  5.         {
  6.                 writeObj();
  7.                 readObj();
  8.         }

  9.         public static void readObj() throws Exception
  10.         {
  11.                 ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.txt"));
  12.                 Person p = (Person)ois.readObject();
  13.                 System.out.println(p);
  14.                 ois.close();
  15.         }

  16.         public static void writeObj() throws IOException
  17.         {
  18.                 ObjectOutputStream oos =
  19.                         new ObjectOutputStream(new FileOutputStream("obj.txt"));
  20.                 oos.writeObject(new Person("lisi",20,"kr"));

  21.                 oos.close();
  22.         }
  23. }
复制代码

  1. import java.io.*;
  2. class Person implements Serializable
  3. {
  4.         public static final long serialVersionUID=42L;
  5.         private String name;
  6.         transient int age;
  7.         static String country="cn";

  8.         Person(String name,int age,String country)
  9.         {
  10.                 this.name=name;
  11.                 this.age=age;
  12.                 this.country=country;
  13.         }

  14.         public String toString()
  15.         {
  16.                 return name+":"+age+":"+country;
  17.         }
  18. }
复制代码


作者: 苏伯亚    时间: 2014-3-29 18:30
Person中初始化的就是cn如果你不调用writeObj()方法 直接调用readObj()方法读的就是Person中初始话的内容。而如果你调用writeObj()则就是给Person覆写了,写入了kr,这样读出的就是kr就不是cn了

作者: 谭荣强    时间: 2014-3-29 20:57
静态变量是不能被序列化的。你运行的时候调用的有问题。将write注释掉在读取就O了。
// writeObj();
    readObj();
结果:lisi:0:cn
作者: leon_hm    时间: 2014-4-1 15:36
苏伯亚 发表于 2014-3-29 18:30
Person中初始化的就是cn如果你不调用writeObj()方法 直接调用readObj()方法读的就是Person中初始话的内容。 ...

country是static值,是不会写到文件中的。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2