1

I read that in Java static field are not serialized. I know that static fields are class level fields. But What is the reason in java that static fields cannot be serialized? If I want to serialized static field how can I serialize it? Any answer

Hussen A
  • 459
  • 2
  • 6
  • 15
  • 1
    Serialization is a thing that happens to objects. To instances. Static fields aren't associated with an object or an instance. (Additionally, having any kind of static state that would need to be serialized is itself a sin.) – Louis Wasserman Mar 19 '16 at 21:20
  • ***If I want to serialized static field how can I serialize it?*** why would you want to do that? static data can always be there available for you as soon as you have access to the class.. – ΦXocę 웃 Пepeúpa ツ Mar 19 '16 at 21:22
  • @Xoce not if it's static mutable state (arguments that that's a terrible idea not withstanding) – Richard Tingle Mar 19 '16 at 23:00
  • Why do you want to serialise the class itself? Knowing that may make offering solutions easier (it's not usually something you'd *want* to do) – Richard Tingle Mar 19 '16 at 23:01

1 Answers1

2

As class level values they are "global" to the all instances of that class.

So what would be the "correct" value when deserializing several instances of such class? There can only be one instance of such values. So static fields are linked to the class and are serialized and deserialized with the class itself not with the different instances.

rpy
  • 3,953
  • 2
  • 20
  • 31
  • Yes, I guess it should be that way but how you can serialize the class itself? – Hussen A Mar 19 '16 at 22:38
  • I just want to know why static field is not serializable and I found some explanation on http://stackoverflow.com/questions/1008023/how-to-serialize-static-data-members-of-a-java-class. Thank you all! – Hussen A Mar 19 '16 at 23:18