• Post Reply Bookmark Topic Watch Topic
  • New Topic

Static variable getting serialized  RSS feed

 
Siyaa Hoffman
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I think there is something wrong in my understanding...
In the following code, the static variable should not be serialized, but I see it as serialized.
import java.io.*;
public class TestStaticSerialize implements Serializable
{
private static String statStr = "Static String";
public TestStaticSerialize()
{
}
public void setStatStr(String str2)
{
statStr = str2;
}
public String getStatStr()
{
return statStr;
}
public static void main(String[] args) throws Exception
{
TestStaticSerialize test1 = new TestStaticSerialize();
test1.setStatStr("New Static String");
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("static.txt"));
out.writeObject(test1);
out.flush();
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("static.txt"));
TestStaticSerialize tt2 = (TestStaticSerialize)in.readObject();
System.out.println(tt2.getStatStr());
}
}
Here, the value printed for tt2.getStatStr() is "New Static String", I was hoping that it should be "Static String". Please let me know where did I get it wrong..
Thanks,
Siyaa
 
Joe Ess
Bartender
Posts: 9426
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A static variable is associated with the class rather than an instance, so the field isn't getting serialized, it's getting set, and subsequently read, from the class. Either remove the static modifier, which would make the variable associated with an instance, or seperate your write and read into different programs. By reading and writing in two seperate programs, the static field associated with the class isn't corrupted with that set. For more info, check out the Object Serialization Tutorial
BTW, Objects get serialized to binary files. Saving them to files with the extension ".txt" doesn't make them text files.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!