黑马程序员技术交流社区
标题:
对象的序列号疑问
[打印本页]
作者:
leon_hm
时间:
2014-3-29 16:04
标题:
对象的序列号疑问
以下是看毕姥爷的视频第21天的时候的代码。运行结果是
lisi:0:kr
而视频中的结果是
lisi:0:cn
为什么我的结果不一样呢?
import java.io.*;
class ObjectStreamDemo
{
public static void main(String[] args) throws Exception
{
writeObj();
readObj();
}
public static void readObj() throws Exception
{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.txt"));
Person p = (Person)ois.readObject();
System.out.println(p);
ois.close();
}
public static void writeObj() throws IOException
{
ObjectOutputStream oos =
new ObjectOutputStream(new FileOutputStream("obj.txt"));
oos.writeObject(new Person("lisi",20,"kr"));
oos.close();
}
}
复制代码
import java.io.*;
class Person implements Serializable
{
public static final long serialVersionUID=42L;
private String name;
transient int age;
static String country="cn";
Person(String name,int age,String country)
{
this.name=name;
this.age=age;
this.country=country;
}
public String toString()
{
return name+":"+age+":"+country;
}
}
复制代码
作者:
苏伯亚
时间:
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