不是说static 变量不能序列化吗?但如下程序:
import java.io.*;
public class DataObject implements Serializable
{
private static int i=0;
private String word=" ";
public void setWord(String word)
{
this.word=word;
}
public void setI(int i)
{
this.i=i;
}
public String toString()
{
return "word:"+word+";i="+i;
}
public static void main(String[] args) throws ClassNotFoundException,FileNotFoundException,IOException
{
DataObject object=new DataObject();
object.setWord("123");
object.setI(2);
System.out.println(object);
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("lql.out"));
out.writeObject(object);
ObjectInputStream in=new ObjectInputStream(new FileInputStream("lql.out"));
DataObject object2=(DataObject)in.readObject();
System.out.println(object2);
}
}
运动后:word=123;i=2;
word=123;i=2;
这如何解释呢?
请帮忙一下,谢谢!
import java.io.*;
public class DataObject implements Serializable
{
private static int i=0;
private String word=" ";
public void setWord(String word)
{
this.word=word;
}
public void setI(int i)
{
this.i=i;
}
public String toString()
{
return "word:"+word+";i="+i;
}
public static void main(String[] args) throws ClassNotFoundException,FileNotFoundException,IOException
{
DataObject object=new DataObject();
object.setWord("123");
object.setI(2);
System.out.println(object);
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("lql.out"));
out.writeObject(object);
ObjectInputStream in=new ObjectInputStream(new FileInputStream("lql.out"));
DataObject object2=(DataObject)in.readObject();
System.out.println(object2);
}
}
运动后:word=123;i=2;
word=123;i=2;
这如何解释呢?
请帮忙一下,谢谢!
println(object.toString())
public class DataObject implements Serializable
{
private static int i=0;
public static Person p=new Person("hello");
public Person p2=new Person("world");
private String word=" ";
public void setWord(String word)
{
this.word=word;
}
public void setI(int i)
{
this.i=i;
}
public String toString()
{
return "word:"+word+";i="+i+":"+p.name+":"+p2.name;
}
public static void main(String[] args) throws ClassNotFoundException,FileNotFoundException,IOException
{
DataObject object=new DataObject();
object.setWord("123");
object.setI(2);
System.out.println(object);
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("lql.out"));
out.writeObject(object);
ObjectInputStream in=new ObjectInputStream(new FileInputStream("lql.out"));
DataObject object2=(DataObject)in.readObject();
System.out.println(object2);
System.out.println(object.p==object2.p);//true
System.out.println(object.p2==object2.p2);//false
}
}
class Person implements Serializable{ public String name;
public Person(String name){
this.name=name;
}
public String toString(){
return name;
}
}并且,就算Person没有implements Serializable,只要是static的也可以读出来
程序一,序列化写到文件
程序二,反序列化读出来,分别在两个main方法里面做,依此运行两个程序,就能看到你想要的结果了.
object.setI(2);
System.out.println(object1);
写入;
object.setI(3);
DataObject object2 = 读出;
System.out.println(object2);就会出现不一样的结果了。