Results 1 to 3 of 3
Thread: static in serialization
- 02-02-2011, 07:22 AM #1
Member
- Join Date
- May 2010
- Posts
- 90
- Rep Power
- 0
static in serialization
hi friends,
i have a doubt in serialization. i have read that static variables are not serialized.
but when i tested it does...?
Java Code:import java.io.*; import java.lang.Exception; class Serializer { public static void main(String ... args) { try { Model obj = new Model(); obj.a += 10; ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("myfile")); oos.writeObject(obj); oos.close(); ObjectInputStream ois = new ObjectInputStream(new FileInputStream("myfile")); obj = (Model)ois.readObject(); ois.close(); System.out.println("a = "+obj.a); System.out.println("b = "+obj.b); } catch(Exception e) { System.out.println(e); } } } class Model implements Serializable { static int a = 7; transient int b = 11; }
whats happening here?
does static variables saved on serialization?
thanks in advance....
- 02-02-2011, 07:45 AM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,375
- Blog Entries
- 7
- Rep Power
- 17
When you instantiate a new Model, the class is loaded and initialized; you set the static member variable to 17. When an object is deserialized its class is loaded and initialized unless it already is; here the class Model is already loaded and initialized so a ends up to be equal to 17. Transient members aren't saved to the stream as you could have noticed.
kind regards,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
- 02-02-2011, 08:09 AM #3
Member
- Join Date
- May 2010
- Posts
- 90
- Rep Power
- 0
Similar Threads
-
Can't make static reference to non-static method -> huh?! Simple car prgm
By enerj in forum New To JavaReplies: 7Last Post: 09-24-2010, 05:09 AM -
non-static variable grade cannot be referenced from a static context
By pictianpravin in forum New To JavaReplies: 3Last Post: 02-11-2010, 09:59 AM -
What is Serialization and de-serialization in Java
By Java Tip in forum java.ioReplies: 0Last Post: 04-04-2008, 02:47 PM -
Error: Non-static method append(char) cannot be referenced from a static context
By paul in forum Advanced JavaReplies: 1Last Post: 08-07-2007, 05:05 AM -
Error: non-static variable height cannot be referenced from a static context at line
By fernando in forum AWT / SwingReplies: 1Last Post: 08-01-2007, 09:25 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks